Find value of sibling key in php array

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

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

    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:

    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!

提交回复
热议问题