Jump to content

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


Go to solution Solved by Barand,

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 post
Share on other sites
  • Solution

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>';
  • Like 1
Link to post
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 post
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 post
Share on other sites
This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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