Find value of sibling key in php array

泄露秘密 提交于 2019-11-29 13:11:17
foreach( $locations as $arr ) {
    if($arr['id'] == $_GET['id']) {
        echo $arr['name'];
        break;
    }
}

That should do the trick.

While looping over the array is the solution for the problem as described, it seems more optimal to change your array to be $id=>$name key-value pairs, instead of named key values if that's all the data in the array, e.g.:

$locations = array( '202' => 'GXP Club - Fable',
                    '204' => 'GXP Club - Gray',
             )

Alternatively, if there's more data, I'd switch to a nested data structure, e.g.:

$locations = array( '202' => array( 'name' => 'GXP Club - Fable', 'prop2' =>$prop2, etc),      
                    '204' => array( 'name' => 'GXP Club - Gray', 'prop2' =>$prop2, etc),
             )

That makes it so you can access data via ID (e.g. $locations[$id]['name']), which seems to be what you'd generally be wanting to do.

You can use array_map function which applies your custom action to each element in given array.

array_map(
    function($arr) { if ($arr['id'] == $_GET['id']) echo $arr['name']; }, 
    $locations
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!