doutongfu9484
doutongfu9484
2014-03-05 20:48
浏览 75
已采纳

在php二维数组中找到元素的官方方法?

Looking at the code above...

$Array = array(array("name"=>"Mickey","type"=>"mouse"),array("name"=>"Donald","type"=>"duck"),array("name"=>"Little Helper","type"=>"eniac"));
$search = "Donald";
foreach($Array as $Item){
    if($Item["name"]==$search) $MyItem = $Item;
}
echo('The item named "'.$search.'" is '.$MyItem["type"]);

... I have the feeling that there is an array function or a better way to find an item inside a bidimensional array. These arrays are like a table. Maybe setting the keys as the index unique values (in this case, the name), but I don't know how to do either.

图片转代码服务由CSDN问答提供 功能建议

查看上面的代码......

  $ Array  = array(array(“name”=>“Mickey”,“type”=>“mouse”),array(“name”=>“Donald”,“type”=>“duck”),数组 (“name”=>“Little Helper”,“type”=>“eniac”)); 
 $ search =“Donald”; 
foreach($ Array as $ Item){
 if($ Item [  “name”] == $ search)$ MyItem = $ Item; 
} 
echo('名为“'。$ search。'”的项目是'。$ MyItem [“type”]); 
   
 
 

...我觉得有一个数组函数或更好的方法来查找二维数组中的项目。 这些数组就像一个表。 也许将键设置为索引唯一值(在本例中为名称),但我不知道如何操作。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongyangben6144
    dongyangben6144 2014-03-05 20:55
    已采纳

    Using the new array_column() function in PHP 5.5

    $Array = array(array("name"=>"Mickey","type"=>"mouse"),array("name"=>"Donald","type"=>"duck"),array("name"=>"Little Helper","type"=>"eniac"));
    $search = "Donald";
    
    $key = array_search(
        $search,
        array_column($Array,'name')
    );
    if($key !== false) {
        $MyItem = $Array[$key];
        echo('The item named "'.$search.'" is '.$MyItem["type"]);
    }
    
    点赞 评论
  • douba3943
    douba3943 2014-03-05 20:55

    If you can recompose the array as:

    array("Mickey"=>"mouse","Donald"=>"duck","Little Helper"=>"eniac");
    

    or

    array("Mickey"=>array("name"=>"mouse"),"Donald"=>array("name"=>"duck"),"Little Helper"=>array("name"=>"eniac"));
    

    and just return by key

    点赞 评论
  • dpzff20644
    dpzff20644 2014-03-05 20:57

    Works for this case:

    echo array_column($Array, 'type', 'name')[$search];
    

    Or with check:

    $names = array_column($Array, 'type', 'name');
    echo isset($names[$search]) ? $names[$search] : 'not found';
    

    To convert to name => type use:

    $Array = array_column($Array, 'type', 'name');
    

    Then after you can just use $Array[$search].

    点赞 评论

相关推荐