Reputation: 2701
I have a multidimensional php array like this
Array
(
[0] => Array
(
[size] => M
[colour] => black
[quantity] => 10
)
[1] => Array
(
[size] => S
[colour] => blue
[quantity] => 10
)
)
and i have another array like this
Array
(
[size] => M
[colour] => black
)
How do I transverse to first array to find the array that matches the second one?
Upvotes: 0
Views: 127
Reputation: 158
Taking a different approach:
$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;
This solution seems correct to me because from your example I'm guessing you are trying to find the quantity. Therefore, the array_diff will return the quantity in the result regardless, resulting in the need to check for just size and color for a match.
Upvotes: 2
Reputation: 55
For Example:
$array1 is your First array and $array2 is your Second array. Then :
$result = array();
foreach ($array1 as $subarray)
{
$check = array_diff($subarray, $array2);
if (empty($check)) {
$result = $subarray;
}
}
Upvotes: 0
Reputation: 30488
Try this one
<?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";
}
}
?>
working example http://codepad.org/iQPxSHKd
Upvotes: 1
Reputation: 3066
Consider first array is "mainarray" and second one is "comparearray"
$result = array();
foreach($mainarray as $marray)
{
if($marray['size'] == $comparearray['size'] && $marray['colour'] == $comparearray['colour'])
{
$result = $marray;
//echo "match found";
}
}
note: if compare array is single array it is applicable. if that also multidimension array you should put foreach for that array also.
Upvotes: 1
Reputation: 5683
Try
$result = array();
foreach ($multi_array as $arr) {
if ($arr['size'] == $one_dimen_arr['size'] && $arr['colour'] == $one_dimen_arr['colour']) {
$result = $arr;
break;
}
}
Upvotes: 0