i have array one:
$array = array( array('id' => 'foo.bar'), array('id' => 'foo'), array('id' => 'foo.baz.bar'), array('id' => 'foo.bar.bar'), );
i can split
id
fields them paths, , i'd sort them tree... tried this:
$result = array(); foreach($array $element) { $path = explode('.', $element['id']); $subtree = $result; while(!empty($path)) { $path_element = array_shift($path); if(empty($path_element)) { $subtree['data'] = $element; } else { if(!is_array($subtree[$path_element])) { $subtree[$path_element] = array(); } $subtree = $subtree[$path_element]; } } }
but load of warnings , empty $res
-array.
php notice: undefined index: foo in tree.php on line 24 php stack trace: php 1. {main}() tree.php:0 php notice: undefined index: bar in tree.php on line 24 php stack trace: php 1. {main}() tree.php:0 php notice: undefined index: foo in tree.php on line 24 php stack trace: php 1. {main}() tree.php:0 php notice: undefined index: foo in tree.php on line 24 php stack trace: php 1. {main}() tree.php:0 php notice: undefined index: baz in tree.php on line 24 php stack trace: php 1. {main}() tree.php:0 php notice: undefined index: bar in tree.php on line 24 php stack trace: php 1. {main}() tree.php:0 php notice: undefined index: foo in tree.php on line 24 php stack trace: php 1. {main}() tree.php:0 php notice: undefined index: bar in tree.php on line 24 php stack trace: php 1. {main}() tree.php:0 php notice: undefined index: bar in tree.php on line 24 php stack trace: php 1. {main}() tree.php:0
(line 24 $s = $s[$pe];
)
any hint?
edit: desired output this
$res = array( 'foo' => array( 'data' => ... 'bar' => array( 'data' => ... 'bar' => array( 'data' => ... ), ), 'baz' => array( 'bar' => array( 'data' => ... ), ), ), );
the data
elements original elements array.
the code below generates following result:
array ( [foo] => array ( [data] => ... [baz] => array ( [bar] => array ( [data] => ... ) ) [bar] => array ( [bar] => array ( [data] => ... ) ) ) )
i renamed of you're variables...
$array = array( array('id' => 'foo.bar'), array('id' => 'foo'), array('id' => 'foo.baz.bar'), array('id' => 'foo.bar.bar'), ); $res = array(); foreach($array $e) { $parts = explode('.', $e['id']); $temp = &$res; foreach($parts $key => $el) { if (!isset($temp[$el])) $temp[$el] = array(); if ($key == count($parts)-1) $temp[$el] = array('data' => '...'); $temp = &$temp[$el]; } } print_r($res);
Comments
Post a Comment