php - multidimensional array, leafs as keys with parent. Recursive iterator -
hello need change structure of multidimensional array parents contains children data children holds info parents
$tab = [ 'movies' => [ 'action', 'drama', 'comedy' => [ 'romance' => ['90th'], 'boring' ] ], 'colors' => [ 'red'=>'light', 'green'=> [ 'dark', 'light' ], 'oragne' ] ];
transfer to
$tab = [ '90th' => [ 'romance' => [ 'comedy' => 'movies' ] ], 'boring' => [ 'comedy' => 'movies' ], 'comedy' => 'movies', 'drama' => 'movies', 'action' => 'movies', 'light' => [ 'red', 'green' => 'colors' ], 'dark' => [ 'green' => 'colors' ], 'oragne' => 'colors', 'green' => 'colors', 'red' ];
i know obtaining leafs use
foreach(new recursiveiteratoriterator(new recursivearrayiterator($tab), recursiveiteratoriterator::leaves_only) $key => $value) { $result[$value] = $key; }
but not work expect.
this partial answer, don't hopes up. maybe expanded solve problem.
for work, first need 'red'=>'light'
'red'=>['light'}
(so looks 'romance' => ['90th']
). gives series of flat arrays, not depth want it. also, not sorted desired output.
function insideout($array, $trail) { foreach($array $key => $value) { $new_trail = $trail; if(is_array($value)) { $new_trail[] = $key; insideout($array[$key], $new_trail); } else { $new_trail[] = $value; print_r($new_trail); } } } insideout($tab, array());
this gives following output:
array ( [0] => movies [1] => action ) array ( [0] => movies [1] => drama ) array ( [0] => movies [1] => comedy [2] => romance [3] => 90th ) array ( [0] => movies [1] => comedy [2] => boring ) array ( [0] => colors [1] => red [2] => light ) array ( [0] => colors [1] => green [2] => dark ) array ( [0] => colors [1] => green [2] => light ) array ( [0] => colors [1] => oragne )
if replace print_r($new_trail);
gives trail "depth" , saves it, problem solved.
i know, know, not of answer , don't expect green check. figued better posting (very little) progress here throwing away.
Comments
Post a Comment