How can I reindex a multi-dimensional array?

倾然丶 夕夏残阳落幕 提交于 2021-01-29 08:15:29

问题


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!


回答1:


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.




回答2:


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);
}



回答3:


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.



来源:https://stackoverflow.com/questions/12091824/how-can-i-reindex-a-multi-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!