我有数组名称$main_array
$main_array = [
[
'product_id' => '1',
'values' => '1"'
],
[
'product_id' => '4',
'values' => '1"'
],
[
'product_id' => '4',
'values' => 'blue'
],
[
'product_id' => '5',
'values' => 'blue'
]
];
我想检查其他数组的值
$check_array = [
'1"','blue'
];
查找product_id 1"
&& blue
都匹配
预期输出::
$output = [
[
'product_id' => '4',
'values' => '1"'
],
[
'product_id' => '4',
'values' => 'blue'
]
];
答案 0 :(得分:0)
您可以使用数组来存储匹配元素,使用产品ID作为键。
$include = [] ;
foreach ($main_array as $key => $item) {
// if values match to $check_array
if (in_array($item['values'], $check_array)) {
// store using product id as key
$pid = $item['product_id'] ;
$include[$pid][] = $key;
}
}
// Filter to keep only items that match with all conditions
$include = array_filter($include, function($a) use ($check_array) {
return count($a) == count($check_array) ;
}) ;
$include = reset($include) ; // Get the first
// Recreate final array :
$out = [] ;
foreach ($include as $elem) {
$out[] = $main_array[$elem] ;
}
print_r($out);
输出:
Array
(
[0] => Array
(
[product_id] => 4
[values] => 1"
)
[1] => Array
(
[product_id] => 4
[values] => blue
)
)
答案 1 :(得分:0)
您可以使用嵌套的foreach循环。假设$ check_array包含两个字段,您可以编写如下代码:
$output = array();
$match_array = array();
//check the first field correspondence
foreach ($main_array as $key1=>$sub_main) {
foreach ($sub_main as $key2=>$item) {
if ($check_array[0] == $item['values']) {
$match_array[] = $item['product_id'];
}
}
}
//try to match the second field
foreach ($main_array as $key1=>$sub_main) {
foreach ($sub_main as $key2=>$item) {
if ($check_array[1] == $item['values']) {
if (in_array($item['product_id'], $match_array) {
$output[] = array($item['product_id'], $check_array[1]);
$output[] = array($item['product_id'], $check_array[2]);
}
}
}
}