Re: create tree from arrays
| From: | Richard Quadling | Date: | Thu, 13 May 2010 10:09:23 +0000 |
| Subject: | Re: create tree from arrays | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-305148@lists.php.net to get a copy of this message | ||
On 13 May 2010 09:51, shahrzad khorrami <shahrzad.khorrami@gmail.com> wrote:
> hi all,
>
> I want to create an array from another array to create json file in my
> format and pass it to a js library....ok.
> I just know that I have to use recursive function... but how? it's hard for
> me to create the new array..
Assuming that nid = 1 / parentID = 0 is the root.
<?php
$Relationships = array();
foreach($Data as $ID => $Row)
{
$Relationships[$ID] = $Row['nid'];
}
foreach($Data as $ID => &$Row)
{
if (0 != $Row['parentID'])
{
$Data[array_search($Row['parentID'], $Relationships)]['children'][] =
&$Row;
}
}
print_r($Data[0]);
?>
outputs ...
Array
(
[nid] => 1
[parentID] => 0
[text] => Dashboard
[cls] => x-btn-icon
[icon] => lib/extjs/resources/images/default/icon/Dashboard.png
[singleClickExpand] => 1
[leaf] => 0
[id] => Dashboard
[children] => Array
(
[0] => Array
(
[nid] => 2
[parentID] => 1
[text] => Dashboard
[cls] => firstExpanded
[icon] => lib/extjs/resources/images/default/tree/s.gif
[singleClickExpand] => 1
[leaf] => 0
[id] =>
[children] => Array
(
[0] => Array
(
[nid] => 3
[parentID] => 2
[text] => Dashboard
[cls] => x-btn-icon
[icon] =>
lib/extjs/resources/images/default/tree/s.gif
[singleClickExpand] => 1
[leaf] => 1
[id] => dashboard
)
)
)
)
)
--
-----
Richard Quadling
"Standing on the shoulders of some very clever giants!"
EE : http://www.experts-exchange.com/M_248814.html
EE4Free : http://www.experts-exchange.com/becomeAnExpert.jsp
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498&r=213474731
ZOPA : http://uk.zopa.com/member/RQuadling