I have a multidimensional array that looks like this:
$trees = array(
array(
\'name\' => \'Parent\',
\'__children\' => array(
code
<?php
$output_array = array();
$input_array = array(
array(
'name'=>'Parent',
'__children' => array(
array(
'name' => 'Child'
),
array(
'name' => 'Second Child'
)
)
)
);
echo"<pre>";
print_r($input_array);
echo"</pre>";
function flatten($arr){
global $output_array;
if(is_array($arr)){
foreach($arr as $key=>$value){
if($key=="name" && !is_array($value)){
$output_array[] = array($key=>$value);
}
elseif(is_array($value)){
flatten($value);
}
}
}
}
flatten($input_array);
echo"<pre>";
print_r($output_array);
echo"</pre>";
Output
//Input array
Array
(
[0] => Array
(
[name] => Parent
[__children] => Array
(
[0] => Array
(
[name] => Child
)
[1] => Array
(
[name] => Second Child
)
)
)
)
//Output Array
Array
(
[0] => Array
(
[name] => Parent
)
[1] => Array
(
[name] => Child
)
[2] => Array
(
[name] => Second Child
)
)
I ended up using something like this, with a lot of inspiration from @Pankrates answer. Thanks a lot.
$trees = $multidimensionalArray;
$flat = array();
$postRepository->flattenRecursive($flat, $trees);
//$flat is now a flattened version of $multidimensionalArray
var_dump($flat);
public function flattenRecursive(array &$flat, array $nested, $parentPrepend = false)
{
foreach( $nested as $item ){
$flat[] = array(
'name' => ($parentPrepend) ? $parentPrepend . '/' . $item['name'] : $item['name']
);
$prepend = $parentPrepend ? $parentPrepend . '/' . $item['name'] : $item['name'];
if(isset($item['__children']))
$this->flattenRecursive($flat, $item['__children'], $prepend);
}
}
Ok I have given this a shot and although it might not be the cleanest solution I think it should get the job done:
function flattenRecursive(array &$flat, $parentkey, array $nested){
$flag = true;
$prepend = '';
foreach( $nested as $k => $val ){
if( is_array($val) ){
if ( $k == '__children' && $flag) {
$prepend = end($flat);
$flag = true;
} else {
$flag = false;
}
flattenRecursive($flat, $prepend , $val);
} else {
$flat[] = $parentkey . ' ' . $val;
}
}
}
function flatten(array $nested){
$flat = array();
flattenRecursive($flat, '', $nested);
return $flat;
}
On a test array (with extra nesting for extra testing) as follows
$trees = array(
array(
'name' => 'Parent',
'__children' => array(
array(
'name' => 'Child',
'__children' => array(
array(
'name' => 'Nest One'
),
array(
'name' => 'Nest Two'
)
)
),
array(
'name' => 'Second Child'
)
)
)
);
$result = flatten($trees);
the var_dump
of $result
looks like the following
array(5) {
[0]=>
string(7) " Parent"
[1]=>
string(13) " Parent Child"
[2]=>
string(22) " Parent Child Nest One"
[3]=>
string(22) " Parent Child Nest Two"
[4]=>
string(20) " Parent Second Child"
}
Hopefully this was what you were looking for