phparraysmultidimensional-arrayfilter

Find the first row of a 2d which contains all required associative elements


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?


Solution

  • 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.