Find value of sibling key in php array

爱⌒轻易说出口 提交于 2019-12-17 16:53:11

问题


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

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

    array (
        "id" => 204,
        "name" => "GXP Club - Gray"
    )
);

What I know (from a GET) is the ID (202). What I would like to display is "Showing results for " ( where $locations[?][id] = $_GET['id'] { echo $locations[?][name] } ) - if you will pardon my use of pseudo code.

Not sure what function is best or if I need to loop over the whole array to find that. Thanks.

Edit: for further clarification. I need to learn the [name] given the [id]


回答1:


foreach( $locations as $arr ) {
    if($arr['id'] == $_GET['id']) {
        echo $arr['name'];
        break;
    }
}

That should do the trick.




回答2:


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.




回答3:


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
);



回答4:


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!



来源:https://stackoverflow.com/questions/12182575/find-value-of-sibling-key-in-php-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!