Wes*_*ter 13 php arrays multidimensional-array
我有一个数组列表(对于这个例子,我正在使用手机).我希望能够搜索多个键/值对并返回它的父数组索引.
例如,这是我的数组:
// $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
)
)
Run Code Online (Sandbox Code Playgroud)
我想要能够做如下的事情:
// 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.
Run Code Online (Sandbox Code Playgroud)
关于我如何能够或应该如何做的任何想法或建议?
Mic*_*ton 16
也许这会很有用:
/**
* 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 ( )
Run Code Online (Sandbox Code Playgroud)
如输出所示,此函数将返回包含符合所有搜索条件的元素的所有键的数组.
您可以使用 array_intersect_key 和 array_intersect 和 array_search
检查array_intersect_key php 手册以获取具有匹配键的项目数组
和array_intesect php 手册以获取具有匹配值的项目的数组
你可以使用数组中的键值 $array[key]
并使用 array_search 获取数组中的键值 $key = array_search('green', $array);
php.net/manual/en/function.array-search.php
我最终做了以下事情。它不漂亮,但效果很好。对于任何阅读的人,请随时使用 DRYer 答案进行更新:
// Variables for this example
$carrier = 'Verizon';
$model = 'Droid X2';
$manufacturer = 'Motorola';
// The foreach loop goes through each key/value of $list_of_phones and checks
// if the given value is found in that particular array. If it is, it then checks
// a second parameter (model), and so on.
foreach ($list_of_phones as $key => $object)
{
if ( array_search($carrier, $object) )
{
if ( array_search($model, $object) )
{
if ( array_search($manufacturer, $object) )
{
// Return the phone from the $list_of_phones array
$phone = $list_of_phones[$key];
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
奇迹般有效。