如何在 PHP 中的多维数组中按 key=>value 进行搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1019076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:39:42  来源:igfitidea点击:

How to search by key=>value in a multidimensional array in PHP

phparrayssearchrecursion

提问by John Kugelman

Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can't say how deep the array will be.

是否有任何快速方法可以获取在多维数组中找到键值对的所有子数组?我不能说阵列有多深。

Simple example array:

简单示例数组:

$arr = array(0 => array(id=>1,name=>"cat 1"),
             1 => array(id=>2,name=>"cat 2"),
             2 => array(id=>3,name=>"cat 1")
);

When I search for key=name and value="cat 1" the function should return:

当我搜索 key=name 和 value="cat 1" 时,函数应该返回:

array(0 => array(id=>1,name=>"cat 1"),
      1 => array(id=>3,name=>"cat 1")
);

I guess the function has to be recursive to get down to the deepest level.

我想这个函数必须是递归的才能深入到最深层次。

回答by John Kugelman

Code:

代码:

function search($array, $key, $value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
             1 => array(id=>2,name=>"cat 2"),
             2 => array(id=>3,name=>"cat 1"));

print_r(search($arr, 'name', 'cat 1'));

Output:

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => cat 1
        )

    [1] => Array
        (
            [id] => 3
            [name] => cat 1
        )

)

If efficiency is important you could write it so all the recursive calls store their results in the same temporary $resultsarray rather than merging arrays together, like so:

如果效率很重要,您可以编写它,以便所有递归调用将其结果存储在同一个临时$results数组中,而不是将数组合并在一起,如下所示:

function search($array, $key, $value)
{
    $results = array();
    search_r($array, $key, $value, $results);
    return $results;
}

function search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key]) && $array[$key] == $value) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        search_r($subarray, $key, $value, $results);
    }
}

The key there is that search_rtakes its fourth parameter by reference rather than by value; the ampersand &is crucial.

关键是search_r通过引用而不是通过值来获取它的第四个参数;&符号&是至关重要的。

FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the callto search_rrather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results).

FYI:如果你有PHP的是旧版本,那么你必须指定在通按基准部电话search_r,而不是在其声明。也就是说,最后一行变成了search_r($subarray, $key, $value, &$results)

回答by jared

How about the SPLversion instead? It'll save you some typing:

SPL版本怎么样?它将为您节省一些输入:

// I changed your input example to make it harder and
// to show it works at lower depths:

$arr = array(0 => array('id'=>1,'name'=>"cat 1"),
             1 => array(array('id'=>3,'name'=>"cat 1")),
             2 => array('id'=>2,'name'=>"cat 2")
);

//here's the code:

    $arrIt = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

 foreach ($arrIt as $sub) {
    $subArray = $arrIt->getSubIterator();
    if ($subArray['name'] === 'cat 1') {
        $outputArray[] = iterator_to_array($subArray);
    }
}

What's great is that basically the same code will iterate through a directory for you, by using a RecursiveDirectoryIterator instead of a RecursiveArrayIterator. SPL is the roxor.

很棒的是,基本上相同的代码将通过使用 RecursiveDirectoryIterator 而不是 RecursiveArrayIterator 为您遍历一个目录。SPL 是 roxor。

The only bummer about SPL is that it's badly documented on the web. But several PHP books go into some useful detail, particularly Pro PHP; and you can probably google for more info, too.

关于 SPL 的唯一遗憾是它在网络上的记录很糟糕。但是有几本 PHP 书籍介绍了一些有用的细节,尤其是 Pro PHP;你也可以谷歌搜索更多信息。

回答by Prasanth Bendra

<?php
$arr = array(0 => array("id"=>1,"name"=>"cat 1"),
             1 => array("id"=>2,"name"=>"cat 2"),
             2 => array("id"=>3,"name"=>"cat 1")
);
$arr = array_filter($arr, function($ar) {
   return ($ar['name'] == 'cat 1');
   //return ($ar['name'] == 'cat 1' AND $ar['id'] == '3');// you can add multiple conditions
});

echo "<pre>";
print_r($arr);

?>

Ref: http://php.net/manual/en/function.array-filter.php

参考:http: //php.net/manual/en/function.array-filter.php

回答by stefgosselin

Came back to post this update for anyone needing an optimisation tip on these answers, particulary John Kugelman's great answer up above.

回来为任何需要有关这些答案的优化提示的人发布此更新,尤其是上面约翰·库格曼 (John Kugelman) 的精彩回答。

His posted function work fine but I had to optimize this scenario for handling a 12 000 row resultset. The function was taking an eternal 8 secs to go through all records, waaaaaay too long.

他发布的函数工作正常,但我必须优化此场景以处理 12 000 行结果集。该函数需要一个永恒的 8 秒来遍历所有记录,太长了。

I simply needed the function to STOP searching and return when match was found. Ie, if searching for a customer_id, we know we only have one in the resultset and once we find the customer_id in the multidimensional array, we want to return.

我只需要该函数来停止搜索并在找到匹配项时返回。即,如果搜索 customer_id,我们知道结果集中只有一个,一旦我们在多维数组中找到 customer_id,我们就想返回。

Here is the speed-optimised ( and much simplified ) version of this function, for anyone in need. Unlike other version, it can only handle only one depth of array, does not recurse and does away with merging multiple results.

这是此功能的速度优化(和大大简化)版本,适用于任何需要的人。与其他版本不同的是,它只能处理一个深度的数组,不会递归,并且不需要合并多个结果。

// search array for specific key = value
public function searchSubArray(Array $array, $key, $value) {   
    foreach ($array as $subarray){  
        if (isset($subarray[$key]) && $subarray[$key] == $value)
          return $subarray;       
    } 
}

This brought down the the task to match the 12 000 records to a 1.5 secs. Still very costlybut much more reasonable.

这降低了将 12 000 条记录匹配到 1.5 秒的任务。仍然非常昂贵,但更合理。

回答by blackmogu

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

对快速版本的小幅改进。

回答by mbdxgdb2

Be careful of linear search algorithms (the above are linear) in multiple dimensional arrays as they have compounded complexity as its depth increases the number of iterations required to traverse the entire array. Eg:

小心多维数组中的线性搜索算法(以上是线性的),因为它们的复杂性增加了,因为其深度增加了遍历整个数组所需的迭代次数。例如:

array(
    [0] => array ([0] => something, [1] => something_else))
    ...
    [100] => array ([0] => something100, [1] => something_else100))
)

would take at the most 200 iterations to find what you are looking for (if the needle were at [100][1]), with a suitable algorithm.

使用合适的算法最多需要 200 次迭代才能找到您要查找的内容(如果指针位于 [100][1])。

Linear algorithms in this case perform at O(n) (order total number of elements in entire array), this is poor, a million entries (eg a 1000x100x10 array) would take on average 500,000 iterations to find the needle. Also what would happen if you decided to change the structure of your multidimensional array? And PHP would kick out a recursive algorithm if your depth was more than 100. Computer science can do better:

在这种情况下,线性算法以 O(n) 执行(排序整个数组中元素的总数),这很糟糕,一百万个条目(例如 1000x100x10 数组)平均需要 500,000 次迭代才能找到针。如果您决定更改多维数组的结构,会发生什么?如果深度超过 100,PHP 会踢出递归算法。计算机科学可以做得更好:

Where possible, always use objects instead of multiple dimensional arrays:

在可能的情况下,始终使用对象而不是多维数组:

ArrayObject(
   MyObject(something, something_else))
   ...
   MyObject(something100, something_else100))
)

and apply a custom comparator interface and function to sort and find them:

并应用自定义比较器接口和函数来排序和查找它们:

interface Comparable {
   public function compareTo(Comparable $o);
}

class MyObject implements Comparable {
   public function compareTo(Comparable $o){
      ...
   }
}

function myComp(Comparable $a, Comparable $b){
    return $a->compareTo($b);
}

You can use uasort()to utilize a custom comparator, if you're feeling adventurous you should implement your own collections for your objects that can sort and manage them (I always extend ArrayObject to include a search function at the very least).

您可以使用uasort()自定义比较器,如果您喜欢冒险,您应该为可以排序和管理它们的对象实现自己的集合(我总是扩展 ArrayObject 以至少包含搜索功能)。

$arrayObj->uasort("myComp");

Once they are sorted (uasort is O(n log n), which is as good as it gets over arbitrary data), binary search can do the operation in O(log n) time, ie a million entries only takes ~20 iterations to search. As far as I am aware custom comparator binary search is not implemented in PHP (array_search()uses natural ordering which works on object references not their properties), you would have to implement this your self like I do.

一旦它们被排序(uasort 是 O(n log n),这与它获取任意数据一样好),二分搜索可以在 O(log n) 时间内完成操作,即一百万个条目只需要约 20 次迭代搜索。据我所知,自定义比较器二进制搜索没有在 PHP 中实现(array_search()使用自然排序,它适用于对象引用而不是它们的属性),你必须像我一样自己实现它。

This approach is more efficient (there is no longer a depth) and more importantly universal (assuming you enforce comparability using interfaces) since objects define how they are sorted, so you can recycle the code infinitely. Much better =)

这种方法更有效(不再有深度),更重要的是通用(假设您使用接口强制执行可比性),因为对象定义了它们的排序方式,因此您可以无限地回收代码。好多了=)

回答by Tristan

Here is solution:

这是解决方案:

<?php
$students['e1003']['birthplace'] = ("Mandaluyong <br>");
$students['ter1003']['birthplace'] = ("San Juan <br>");
$students['fgg1003']['birthplace'] = ("Quezon City <br>");
$students['bdf1003']['birthplace'] = ("Manila <br>");

$key = array_search('Delata Jona', array_column($students, 'name'));
echo $key;  

?>

回答by Vitalii Fedorenko

$result = array_filter($arr, function ($var) {   
  $found = false;
  array_walk_recursive($var, function ($item, $key) use (&$found) {  
    $found = $found || $key == "name" && $item == "cat 1";
  });
  return $found;
});

回答by Pramendra Gupta

http://snipplr.com/view/51108/nested-array-search-by-value-or-key/

http://snipplr.com/view/51108/nested-array-search-by-value-or-key/

<?php

//PHP 5.3

function searchNestedArray(array $array, $search, $mode = 'value') {

    foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) {
        if ($search === ${${"mode"}})
            return true;
    }
    return false;
}

$data = array(
    array('abc', 'ddd'),
    'ccc',
    'bbb',
    array('aaa', array('yyy', 'mp' => 555))
);

var_dump(searchNestedArray($data, 555));

回答by radhe

function in_multi_array($needle, $key, $haystack) 
{
    $in_multi_array = false;
    if (in_array($needle, $haystack))
    {
        $in_multi_array = true; 
    }else 
    {
       foreach( $haystack as $key1 => $val )
       {
           if(is_array($val)) 
           {
               if($this->in_multi_array($needle, $key, $val)) 
               {
                   $in_multi_array = true;
                   break;
               }
           }
        }
    }

    return $in_multi_array;
}