标准数组到树数组

时间:2017-08-29 04:01:54

标签: php

我有这样的数组;

enter image description here

但是我想通过像这样使用级别键来设置数组;

enter image description here

我正在使用此代码,但我知道这不是一个合适的解决方案,所以你怎么能帮助我?

comparePassword

2 个答案:

答案 0 :(得分:0)

你让它变得复杂,你可以这样做

<?php
  $arrs = [["tag"=>"one","level"=>1],["tag"=>"two","level"=>2],["tag"=>"three","level"=>3]];
  $new = array();
  function setLevel($single){ 
    if($single['level']==1){
      $new["tag"] = $single['tag'];
    }else{
      $single['level'] -= 1;
      $new["array"] = setLevel($single);
    }
    return $new;
  }
  $temp = array();
  foreach($arrs as $key=>$arr){
    $temp = array_merge_recursive($temp,setLevel($arr));
  }
  print_r($temp);
?>

演示1:https://eval.in/851578

演示2:https://eval.in/851584

演示3:https://eval.in/851585

演示4:https://eval.in/851586

答案 1 :(得分:0)

你可以做一个递归函数。

$tree = setTree($array, 0);

function setTree($v, $i){
    $tree = null;
    $level = $v[$i]['level'];
    if($level > 0){
        $next = $i + 1;
        if(isset($v[$next]))
            $tree = array('0' => array('tag' => $v[$i]['tag'], 'array' => setTree($v, $next)));
        else{
            $tree = array('0' => array('tag' => $v[$i]['tag']));
        }
    }
    return $tree;
}

print_r($tree);