Jump to content

Flatten a 2D array to only contain values contained in all 2D


FlatulentBadger

Recommended Posts

Hi there, 

 

   I'm new here and fairly new to PHP, so be gentle please.

 

I have a 2D array such as: 

Array
(
    [0] => Array
        (
            [0] => 28
            [1] => 6
        )
    [1] => Array
        (
            [0] => 6
        )
    [2] => Array
       (
            [0] => 61
            [1] => 6
            [2] => 28
        )
)

From which I need to end up with an array containing only the elements that exist in all the 2nd dimensions.

 

In this case it would be just 6.

 

I could iterate over everything starting with the smallest array  " [0] => Array  ( [0] => 6 )", but it seems a bit clumsy, and I was wondering if I have missed any PHP array function that may make this easier,  or if anyone has any better suggestions?

 

Cheers,

   Bob.

 
Link to comment
Share on other sites

 

You mean like this?

$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

foreach ($cars[1] as $v) {
    echo  "$v<br>";
}
?>

I don't, I appreciate my question may not be entirely clear though, too much mixing of languages, and beer. :) 

 

Barand, got the jist. 

Link to comment
Share on other sites

 

Use array_intersect to check for common values

$data = [   [28, 6],  [6], [61,6,28]  ];
        
$result = [];
foreach ($data as $arr) {
    $result = empty($result) ? $arr : array_intersect($result, $arr);
}

// view result
echo '<pre>', print_r($result, 1), '</pre>';

Thanks Barand, this is exactly what I was after, I am off for a bit of a deeper dive into the array_intersect docs now. :)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.