我有一个像这样的多维php数组
Array
(
[0] => Array
(
[size] => M
[colour] => black
[quantity] => 10
)
[1] => Array
(
[size] => S
[colour] => blue
[quantity] => 10
)
)
我有另一个这样的数组
Array
(
[size] => M
[colour] => black
)
如何横向第一个数组找到与第二个数组匹配的数组? 对于如何解决这个问题我完全不知道。感谢
答案 0 :(得分:2)
采取不同的方法:
$multiArray = array(array('size' => 'M',
'color' => 'black',
'quantity' => '10'),
array('size' => 'S',
'color' => 'blue',
'quantity' => 10));
$otherArray = array('size' => 'S',
'color' => 'blue',
'quantity' => 10)
$message = "Match not found!";
foreach($multiArray as $array) {
$result = array_diff($array, $otherArray);
if(isset($result['size']) or isset($result['color'))
continue;
else
$message = "Found a match!\n Size: {$array['size']}\n Color: {$array['color']}\n Quantity: {$array['quantity']}";
}
echo $message;
这个解决方案对我来说似乎是正确的,因为从你的例子中我猜测你正试图找到数量。因此,array_diff将返回结果中的数量,因此需要检查匹配的大小和颜色。
答案 1 :(得分:1)
考虑第一个数组是“mainarray”,第二个数组是“comparearray”
$result = array();
foreach($mainarray as $marray)
{
if($marray['size'] == $comparearray['size'] && $marray['colour'] == $comparearray['colour'])
{
$result = $marray;
//echo "match found";
}
}
注意:如果比较数组是单个数组,则适用。如果那也是multidimension数组你也应该为该数组放置foreach。
答案 2 :(得分:1)
试试这个
<?php
$arr1 = array(array("size"=>"M","colour" => "black"),array("size"=>"S","colour" => "blue"));
$arr2 = array("size"=>"M","colour" => "black");
print_r($arr1);
print_r($arr2);
foreach($arr1 as $array)
{
if($array['size'] == $arr2['size'] && $array['colour'] == $arr2['colour'])
{
echo "matches";
}
}
?>
答案 3 :(得分:0)
尝试
$result = array();
foreach ($multi_array as $arr) {
if ($arr['size'] == $one_dimen_arr['size'] && $arr['colour'] == $one_dimen_arr['colour']) {
$result = $arr;
break;
}
}
答案 4 :(得分:0)
例如:
$ array1是你的第一个数组,$ array2是你的第二个数组。然后:
$result = array();
foreach ($array1 as $subarray)
{
$check = array_diff($subarray, $array2);
if (empty($check)) {
$result = $subarray;
}
}