0

我有一个像这样的多维php数组

Array
(
    [0] => Array
        (
            [size] => M
            [colour] => black
            [quantity] => 10
        )

    [1] => Array
        (
            [size] => S
            [colour] => blue
            [quantity] => 10
        )

)

我有另一个这样的数组

Array
(
    [size] => M
    [colour] => black
)

我如何横向到第一个数组以找到与第二个匹配的数组?我完全不知道如何去做。谢谢

4

5 回答 5

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 无论如何都会返回结果中的数量,导致需要检查大小和颜色是否匹配。

于 2012-09-30T11:42:09.910 回答
1

考虑第一个数组是“mainarray”,第二个是“comparearray”

$result = array();
    foreach($mainarray as $marray)
    {
      if($marray['size'] == $comparearray['size'] && $marray['colour'] == $comparearray['colour'])
    {
       $result = $marray;
    //echo "match found";
    }
    }

注意:如果比较数组是单个数组,则适用。如果那也是多维数组,您也应该为该数组放置 foreach 。

于 2012-09-30T11:20:59.530 回答
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";
  }
}
?>

工作示例http://codepad.org/iQPxSHKd

于 2012-09-30T11:27:48.207 回答
0

尝试

$result = array();
foreach ($multi_array as $arr) {
  if ($arr['size'] == $one_dimen_arr['size'] && $arr['colour'] == $one_dimen_arr['colour']) {
    $result = $arr;
    break;
  }
}
于 2012-09-30T11:21:01.793 回答
0

例如:

$array1 是您的第一个数组, $array2 是您的第二个数组。然后 :

$result = array();
foreach ($array1 as $subarray)
{
    $check = array_diff($subarray, $array2);
    if (empty($check)) {
        $result = $subarray;
    }
}
于 2012-09-30T11:38:05.103 回答