Question

I'm using this function to calculate the difference between 2 multi-dimensional arrays:

/**
 * http://www.php.net/manual/en/function.array-diff.php#91756
 * @param $array1
 * @param $array2
 * @return array
 */

function arrayRecursiveDiff($array1, $array2){
    $aReturn = array();

    foreach ($array1 as $mKey => $mValue) {
        if (array_key_exists($mKey, $array2)) {
            if (is_array($mValue)) {
                $aRecursiveDiff = arrayRecursiveDiff($mValue, $array2[$mKey]);
                if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
            } else {
                if ($mValue != $array2[$mKey]) {
                    $aReturn[$mKey] = $mValue;
                }
            }
        } else {
            $aReturn[$mKey] = $mValue;
        }
    }
    return $aReturn;
}

It works perfect, bar just one tiny issue:

array(2) {
  ["installed"]=>
  array(3) {
    [3]=>
    string(9) "somevalue1"
    [4]=>
    string(7) "somevalue2"
    [5]=>
    string(5) "somevalue3"        
  }
  ["backend"]=>
  array(1) {
    ["preload"]=>
    array(2) {
      [0]=>
      string(7) "somevalue4"
      [1]=>
      string(10) "somevalue5"
    }
  }
}

As you can see, the sub array "installed" must be re-indexed. In fact I need to recursively reindex this array (or better yet, I need the arrayRecursiveDiff function to return a correctly indexed array). I have tried different ways but seem like my brain is fried for now!

Was it helpful?

Solution

Maybe this function will solve your issue

var_dump(array_map("array_values",arrayRecursiveDiff($a,$b)));

Edit: This one keeps non-digit indexes:

var_dump(array_map(create_function('$x','$k = key($x); return (is_numeric($k)) ? array_values($x) : $x;'),$aDiff));

Note that this function only works for level 2 array-reindex.

OTHER TIPS

try this. sort function will help you

 $array = array (
  "installed"=>
  array (     
    3 =>     "somevalue1",
    4 =>     "somevalue2",
    5 =>     "somevalue3"
  ),
  "backend"=>
  array (
    "preload"=>
    array(
      0=>
      "somevalue4",
      1=>
      "somevalue5"
    )
  )
);
var_dump($array);
sort($array['installed']);
var_dump($array);

loop through variable and use sort that will help you recursively.

foreach($array as $tmparray){
   $newArray = sort($tmparray);
var_dump($newArray);
}

You can re-index an array like this: $arr = array_values($arr);

I would post the code to re-index recursively, but it's not really hard, you should try it yourself and then post the code here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top