Find value of sibling key in php array

前端 未结 4 1563
野的像风
野的像风 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:01

    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
    );
    
    0 讨论(0)
  • 2020-12-06 23:02

    Doing this with PHP's built-in array functions* avoids a foreach loop:

    <?php
    $locations = [["id"=>202, "name"=>"GXP Club - Fable"], ["id"=>204, "name"=>"GXP Club - Gray"]];
    
    $col = array_search(array_column($locations, "id"), $_GET["id"]);
    echo $locations[$col]["name"];
    

    Or, using a different method:

    <?php
    $locations = [["id"=>202, "name"=>"GXP Club - Fable"], ["id"=>204, "name"=>"GXP Club - Gray"]];
    
    $result = array_filter($locations, function($v){ return $v["id"] == $_GET["id"]; });
    echo array_shift($result)["name"];
    

    * Notably, array_column() was not available until PHP 5.5, released 10 months after this question was asked!

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-06 23:17
    foreach( $locations as $arr ) {
        if($arr['id'] == $_GET['id']) {
            echo $arr['name'];
            break;
        }
    }
    

    That should do the trick.

    0 讨论(0)
提交回复
热议问题