我通过添加对不同比较运算符的支持来扩展 @MichaelRushton 的代码:
function multi_array_search ($array, $search) {
$result = [];
foreach ($array as $key => $value) { //iterate over each array element
foreach ($search as $k => $v) { //iterate over each search condition
$operator = $v[0];
$searchField = $v[1];
$searchVal = $v[2];
switch ($operator) {
case '=':
$cond = ($value[$searchField] != $searchVal);
break;
case '!=':
$cond = ($value[$searchField] == $searchVal);
break;
case '>':
$cond = ($value[$searchField] <= $searchVal);
break;
case '<':
$cond = ($value[$searchField] >= $searchVal);
break;
case '>=':
$cond = ($value[$searchField] < $searchVal);
break;
case '<=':
$cond = ($value[$searchField] > $searchVal);
break;
}
//if the array element does not meet the search condition then continue to the next element
if ((!isset($value[$searchField]) && $value[$searchField] !== null) || $cond) {
continue 2;
}
}
$result[] = $key; //add the array element's key to the result array
}
return $result;
}
//incoming data:
$phonesList = [
0 => [
'Manufacturer' => 'Apple',
'Model' => 'iPhone 3G 8GB',
'Carrier' => 'AT&T',
'Cost' => 100000
],
1 => [
'Manufacturer' => 'Motorola',
'Model' => 'Droid X2',
'Carrier' => 'Verizon',
'Cost' => 120000
],
2 => [
'Manufacturer' => 'Motorola',
'Model' => 'Droid X2',
'Carrier' => 'Verizon',
'Cost' => 150000
]
];
var_dump(multi_array_search($phonesList,
[ ['=', 'Manufacturer', 'Motorola'],
['>', 'Cost', '130000'] ]
));
//output:
array(1) { [0]=> int(2) }