doujiepin5547
2018-06-01 08:22
浏览 50
已采纳

递归函数将多维数组中的特定键移动到其级别的底部

I'm looking for a php (sort?)function which move a specific key ('current_files') to the bottom of its array level.

I have sth like that:

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

I need this:

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

I know that i need a recursive function like arr_multisort but i dont understand it -_-

图片转代码服务由CSDN问答提供 功能建议

我正在寻找一个移动特定键的php(sort?)函数('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这样的递归函数,但我不明白它-_-

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • dpauxqt1281 2018-06-01 09:00
    最佳回答

    Try this

    Written a common function just call that function to move down any key by passing the specific key as argument.

    function sortArrayByKey(&$array, $search_key) {
        $searched_key_arr = array();
        foreach ($array as $k => &$values) {
            if (array_key_exists($search_key, $values)) {
                sortArrayByKey($values, $search_key);
            } else if ($k == $search_key) {
                $searched_key_arr[$k] = $values;
                unset($array[$k]);
            }
        }
        if (!empty($searched_key_arr)) {
            foreach ($searched_key_arr as $key => $val) {
                $array[$key] = $val;
            }
        }
        return $array;
    }
    
    $arr = $this->sortArrayByKey($data, 'current_files'); //$data is your input array
    print_r($arr);
    
    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题