Find value of sibling key in php array

前端 未结 4 1573
野的像风
野的像风 2020-12-06 22:32

I have an array in PHP, here is a snippet:

$locations = array(
    array(
        \"id\" => 202,
        \"name\" => \"GXP Club - Fable\"
    ),

    a         


        
4条回答
  •  难免孤独
    2020-12-06 23:05

    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.

提交回复
热议问题