toffler
toffler

Reputation: 1233

php - check multidimensional array for values that exists in more than 1 subarray

Following simplified multidimensional array given:

$input = Array 
(
    [arr1] => Array
        (
            [0] => JAN2016
            [1] => MAI2013
            [2] => JUN2014
        }
    [arr2] => Array
        (
            [0] => APR2016
            [1] => DEC2013
            [2] => JUN2014
        }
    [arr3] => Array
        (
            [0] => JAN2016
            [1] => MAI2020
            [2] => JUN2022
        }
)

I want to check for elements, that exists in more than 1 subarray. An ideal output would be:

$output = Array
(
    [JUN2014] => Array
        (
            [0] => arr1
            [1] => arr2
        )
    [JAN2016] => Array
        (
            [0] => arr1
            [1] => arr3
        )
)

I'm currently stucked in a nested foreach because i need to look all silblings of the outer foreach and don't know how to accomplish that.

  foreach($input as $k=>$values)
  {
      foreach($values as $value)
      {
          //check if value exists in array k+1....n
          //if true, safe to output.
      } 
  }

Upvotes: 1

Views: 55

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94662

You are almost all the way there

$new = [];

foreach($input as $k=>$values) {
    foreach($values as $value) {
        $new[$value][] = $k;
    } 
}

The $new array should look just as you want it

Upvotes: 3

u_mulder
u_mulder

Reputation: 54831

Extended solution which filters subarrays:

$newArray = [];
foreach($input as $k=>$values)
{
    foreach($values as $value)
    {
        $newArray[$value][] = $k;
    } 
}
print_r(array_filter(
    $newArray, 
    function($v) { return 1 < count($v); }
));

Sample fiddle here.

Upvotes: 2

Related Questions