首页 > 解决方案 > 递归函数将多维数组中的特定键移动到他的级别的底部

问题描述

我正在寻找一个 php(排序?)函数,它将特定键('current_files')移动到其数组级别的底部。

我有这样的:

[A] => [
     [current_files] => [
           [0] => ...
           [1] => ...  
     ]
     [D] => [
          [G] => [...]   
          [current_files] => [...]
          [B] => [...]
     ]
]
[current_files] => [...]
[K] => [...]

我需要这个:

[A] => [
     [D] => [
          [G] => [...]   
          [B] => [...]
          [current_files] => [...]
     ]
     [current_files] => [
           [0] => ...
           [1] => ...  
     ]
]
[K] => [...]
[current_files] => [...]

我知道我需要一个像 arr_multisort 这样的递归函数,但我不明白 -_-

标签: phparrayssortingrecursionmultidimensional-array

解决方案


好吧,既然您已经知道要移动的项目的键,那么使用递归函数可以很简单。您使用 '&' 简单地将数组作为参考传递。

function moveCurrentFiles(&$array) {
    //first move current_files to the end of the array
    if (isset($array["current_files"])) {
        $currentFiles = $array["current_files"];
        //unset then reset value to "move" it to the end
        unset($array["current_files"]);
        $array["current_files"] = $currentFiles;
    }

    //loop through array items to check if any of them are arrays
    foreach($array as &$value) {
         if (is_array($value)) {
             //recursively call this function on that array
             moveCurrentFiles($value);
         }
    }
}

推荐阅读