PHP Convert single dimensional array to nested arr

2019-08-16 00:48发布

问题:

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