douni1396 2010-06-15 18:27
浏览 82
已采纳

PHP:在数组中查找具有特定属性值的元素

I'm sure there is an easy way to do this, but I can't think of it right now. Is there an array function or something that lets me search through an array and find the item that has a certain property value? For example:

$people = array(
  array(
    'name' => 'Alice',
    'age' => 25,
  ),
  array(
    'name' => 'Waldo',
    'age' => 89,
  ),
  array(
    'name' => 'Bob',
    'age' => 27,
  ),
);

How can I find and get Waldo?

  • 写回答

3条回答 默认 最新

  • doq13207 2010-06-15 18:32
    关注

    With the following snippet you have a general idea how to do it:

    foreach ($people as $i => $person)
    {
        if (array_key_exists('name', $person) && $person['name'] == 'Waldo')
            echo('Waldo found at ' . $i);
    }
    

    Then you can make the previous snippet as a general use function like:

    function SearchArray($array, $searchIndex, $searchValue)
    {
        if (!is_array($array) || $searchIndex == '')
            return false;
    
        foreach ($array as $k => $v)
        {
            if (is_array($v) && array_key_exists($searchIndex, $v) && $v[$searchIndex] == $searchValue)
                return $k;
        }
    
        return false;
    }
    

    And use it like this:

    $foundIndex = SearchArray($people, 'name', 'Waldo'); //Search by name
    $foundIndex = SearchArray($people, 'age', 89); //Search by age
    

    But watch out as the function can return 0 and false which both evaluates to false (use something like if ($foundIndex !== false) or if ($foundIndex === false)).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据