[ create a new paste ] login | about

Link: http://codepad.org/EwyrjwdU    [ raw code | output | fork ]

PHP, pasted on Nov 26:
<?php
$fruits = array(
  array("fruits", "yellow", "pineapple"),
  array("fruits", "yellow", "lemon"),
  array("fruits", "red", "apple"),
  array("fruits", "red", "tomato"),
);

// Convert array to nested array
function nest($leaf)
{
  if (count($leaf) > 1)
  {
    $key = array_shift($leaf);
    
    return array($key => nest($leaf));
  }
  else
  {
    return $leaf;
  }
}

$tree = array();

foreach($fruits as $fruit)
{
  // Convert each fruit to a nested array and merge recursively
  $tree = array_merge_recursive($tree, nest($fruit));
}

print_r($tree);

?>


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Array
(
    [fruits] => Array
        (
            [yellow] => Array
                (
                    [0] => pineapple
                    [1] => lemon
                )

            [red] => Array
                (
                    [0] => apple
                    [1] => tomato
                )

        )

)


Create a new paste based on this one


Comments: