我有一个数组列表(在这个例子中我使用的是手机)。我希望能够搜索多个键/值对并返回它的父数组索引。
例如,这是我的数组:
// $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
)
)
我希望能够执行以下操作:
// 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.
关于我可以或应该如何做到这一点有什么想法或建议吗?
最佳答案
也许这会有用:
/**
* 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 ( )
如输出所示,此函数将返回一个包含所有键的数组,这些键的元素满足所有搜索条件。
关于PHP 在数组中搜索多个键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13923524/