Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array_walk multidimensional array

I got three arrays with some kind of hierarchical predefined terms

array("fruits", "yellow", "pineapple");
array("fruits", "yellow", "lemon");
array("fruits", "red", "apple");

And I have an assoc array which has a kind of hierachy:

array('fruits'=>array('red'=>array('tomato')));

How can I push the terms of my three array at the right place that I get:

array('fruits'=>array('yellow'=>array('pineapple','lemon'),'red'=>array('tomato','apple')));

Do I use array_walk? Or array_walk_recursive? What should I use?

Best, Joerg

like image 948
JoergP Avatar asked Nov 26 '11 10:11

JoergP


2 Answers

You convert each fruit to a nested array, then you merge using array_merge_recursive().

Here a working example (also on Codepad):

$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);
like image 67
Gustav Bertram Avatar answered Nov 14 '22 02:11

Gustav Bertram


$fruits[] = array("fruits", "yellow", "pineapple");
$fruits[] = array("fruits", "yellow", "lemon");
$fruits[] = array("fruits", "red", "apple");

foreach($fruits as $fruit) {
  $multifruit[$fruit[0]][$fruit[1]][] = $fruit[2];
}

print_r($multifruit);

/* yields:
Array
(
    [fruits] => Array
        (
            [yellow] => Array
                (
                    [0] => pineapple
                    [1] => lemon
                )

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

        )

)
*/

Does exactly what you want. The last [] on the left side of the assignment appends the right side rather than overwriting any existing value if any exists.

like image 1
abcde123483 Avatar answered Nov 14 '22 04:11

abcde123483