PHP在数组中搜索多个键/值对 [英] PHP Search an Array for multiple key / value pairs
本文介绍了PHP在数组中搜索多个键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个阵列列表(在此示例中,我正在使用手机).我希望能够搜索多个键/值对并返回其父数组索引.
I have a array list (for this example I'm using cell phones). I'm wanting to be able to search for multiple key/value pairs and return it's parent array index.
例如,这是我的数组:
// $list_of_phones (array)
Array
(
[0] => Array
(
[Manufacturer] => Apple
[Model] => iPhone 3G 8GB
[Carrier] => AT&T
)
[1] => Array
(
[Manufacturer] => Motorola
[Model] => Droid X2
[Carrier] => Verizon
)
)
我希望能够执行以下操作:
I'm wanting to be able to do something like the following:
// This is not a real function, just used for example purposes
$phone_id = multi_array_search( array('Manufacturer' => 'Motorola', 'Model' => 'Droid X2'), $list_of_phones );
// $phone_id should return '1', as this is the index of the result.
关于如何或应该如何做的任何想法或建议?
Any ideas or suggestions on how I can or should do this?
推荐答案
这可能会有用:
/**
* Multi-array search
*
* @param array $array
* @param array $search
* @return array
*/
function multi_array_search($array, $search)
{
// Create the result array
$result = array();
// Iterate over each array element
foreach ($array as $key => $value)
{
// Iterate over each search condition
foreach ($search as $k => $v)
{
// If the array element does not meet the search condition then continue to the next element
if (!isset($value[$k]) || $value[$k] != $v)
{
continue 2;
}
}
// Add the array element's key to the result array
$result[] = $key;
}
// Return the result array
return $result;
}
// Output the result
print_r(multi_array_search($list_of_phones, array()));
// Array ( [0] => 0 [1] => 1 )
// Output the result
print_r(multi_array_search($list_of_phones, array('Manufacturer' => 'Apple')));
// Array ( [0] => 0 )
// Output the result
print_r(multi_array_search($list_of_phones, array('Manufacturer' => 'Apple', 'Model' => 'iPhone 6')));
// Array ( )
如输出所示,此函数将返回一个包含所有满足搜索条件的元素的所有键组成的数组.
As the output shows, this function will return an array of all keys with elements which meet all the search criteria.
这篇关于PHP在数组中搜索多个键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文