PHP Convert single dimensional array to nested array

烈酒焚心 提交于 2019-12-25 13:15:17

问题


How do I convert an 'N' elements single dimensional array to 'N' level nested array in PHP ?

Example:

Input:

$input = array('Orange','Apple','Banana');

Expected Output:

$output = array(
    'name' => 'Banana',
    'sub_category' => array(
         'name' => 'Apple',
         'sub_category' => array(
             'name' => 'Orange'
);

This is my code:

  $categories = array('Orange','Apple','Banana');
  $count = count($categories);
  for($i=0;$i<=$count;$i++){
    if(isset($categories[$i+1])){
      $parent = $categories[$i+1]; // parent      
        $categories[$i+1]=array(
          'name' => $categories[$i+1],
          'sub_category' => array('name' => $categories[$i])
        );
    }   
  }
  $categories = $categories[$count-1];
  var_dump($categories);

My code is sloppy and I also get the following incorrect output:

$output = array(
    'name' => 'Banana',
    'sub_category' => array(
       'name' => array(  
         'name' => 'Apple',
         'sub_category' => array(
             'name' => 'Orange'
       );
);

Edit 1:

The problem/solution provided here does not seem to be answering my question.


回答1:


You could use simple recursion technique:

function toNestedArray(array $input, array $result = [])
{
    $result = ['name' => array_pop($input)];
    if (count($input)) {
        $result['sub_category'] = toNestedArray($input, $result);
    }

    return $result;
}



回答2:


$categories = array('Orange','Apple','Banana');
  $count = count($categories);
  $categories2=array();
  for($i=$count-1;$i>0;$i--){
      if($i-2>-1){

          $categories2=array(
          'name'=>$categories[$i],
          'sub_category'=>array('name'=>$categories[$i-1],'sub_categories'=>array('name'=>$categories[$i-2]))
          ); 
      }
  }
  echo "<pre>";
  print_r($categories2);
  echo "</pre>";



回答3:


A simple option is to loop over the $input array, building the $output array from inside to out.

$output = array();
foreach ($input as $name) {
    if (empty($output)) {
        $output = array("name" => $name);
    } else {
        $output = array("name" => $name, "sub_category" => $output);
    }
}


来源:https://stackoverflow.com/questions/46717139/php-convert-single-dimensional-array-to-nested-array

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