Search code examples
phparraysmultidimensional-arrayfilterarray-difference

Keep only second level values in an associative 2d array which are not found in another associative 2d array


I've created a function to facilitate using array_diff() with two 2d arrays, but it does not suffice.

<?php
$arraySession = array(
    'sampleA' => array('1', '2', '3'),
    'sampleB' => array('1', '2', '3'),
);

$arrayPost = array(
    'sampleA' => array('1'),
    'sampleB' => array('1', '2'),
);

result should be:

array(
   'sampleA' => array('2', '3')
   'sampleB' => array('3'),
)

my existing function:

public function array_diff_multidimensional($session, $post) { 
    $result = array();
    foreach ($session as $sKey => $sValue) {
        foreach ($post as $pKey => $pValue) {
            if ((string) $sKey == (string) $pKey) {
                $result[$sKey] = array_diff($sValue, $pValue);
            } else {
                $result[$sKey] = $sValue;
            }
        }
    }
    return $result;
}

Solution

  • Not my function and not tested by me, but this was one of the first comments at php.net/array_diff (credit goes to thefrox at gmail dot com)

    <?php
    function multidimensional_array_diff($a1, $a2) {
        $r = array();
    
        foreach ($a2 as $key => $second) {
            foreach ($a1 as $key => $first) {
              if (isset($a2[$key])) {
                  foreach ($first as $first_value) {
                      foreach ($second as $second_value) {
                          if ($first_value == $second_value) {
                              $true = true;
                              break;
                          }
                      }
                      if (!isset($true)) {
                          $r[$key][] = $first_value;
                      }
                      unset($true);
                  }
              } else {
                  $r[$key] = $first;
              }
            }
        }
        return $r;
    }
    ?>