从父子关系构建关联数组

时间:2012-10-22 04:25:10

标签: php mysql recursion

我一直在使用ALMOST为我工作的功能,我来自 HERE ,但它添加了一个我不想要的额外数组。信息存储在我的数据库中,如下所示:

enter image description here

方式

private function buildCategories($array,$parent)
{
    $result = array();
    foreach($array as $row)
    {
        if($row['parent'] == $parent)
        {
            $result[$row['category_name']] = $this->buildCategories($array,$row['category_id']);
        }
    }
    return $result;
}
$json = json_encode($this->buildCategories($array,NULL));
return $json;

我想要这个:

{"reloading":{"components","presses and dies","tumblers & scales","tools & accessories","shotshell reloading"}

但我得到的是:

{"reloading":{"components":[],"presses and dies":[],"tumblers & scales":[],"tools & accessories":[],"shotshell reloading":[]}

注意:我问了一个类似的问题,但不是建立一个关联数组。因为它不像我最初的要求,我认为需要另一个线程。

1 个答案:

答案 0 :(得分:6)

你可以得到这个:

{"reloading":["components","presses and dies","tumblers & scales","tools & accessories","shotshell reloading"]}

代码:

private function buildCategories($array,$parent) 
{
    $result = array();
    foreach($array as $row) {
        if($row['parent'] == $parent) {
            if ($row['parent'] == NULL) {
                $result[$row['category_name']] = $this->buildCategories($array,$row['category_id']);
            } else {
                $result[] = $row['category_name'];
            }
        }
    }
    return $result; 
}