Php array_walk multidimensional array

I got three arrays with some hierarchical predefined terms

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

And I have an associative array that has a kind of hierarchy:

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

How can I click the terms of my three arrays in the right place that I get:

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

Am I using array_walk? Or array_walk_recursive? What should i use?

Best, Jรถrg

+4
source share
3 answers

You convert each fruit into a nested array, then you concatenate with array_merge_recursive () .

Here is 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); 
+3
source
 $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 ) ) ) */ 

This is exactly what you want. The last [] on the left side of the assignment adds the right side, rather than overwriting any existing value, if it exists.

+1
source
 <?php $fruits[] = array("fruits", "yellow", "pineapple"); $fruits[] = array("fruits", "yellow", "lemon"); $fruits[] = array("fruits", "red", "apple"); $fruits[] = array("fruits", "blue", "small","blueberry"); $fruits[] = array("fruits", "blue", "bluefruit"); $fruits[] = array("fruits", "multicolor-fruit"); function deeper(&$multifruit, $fruit) { if (count($fruit)>2) { $shifted = array_shift($fruit); deeper($multifruit[$shifted], $fruit); return $multifruit; } else { return $multifruit[$fruit[0]][] = $fruit[1]; } } foreach($fruits as $fruit) { deeper($multifruit, $fruit); } print_r($multifruit); ?> 

Here you will find a more general solution to your problem. It took me a while, so I hope you appreciate it :)

0
source

Source: https://habr.com/ru/post/1383174/


All Articles