1

I've been playing around with a function that ALMOST works for me that I got from HERE, but it adds an extra array that I do NOT want. The information is stored in my database like so:

enter image description here

Method

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;

I want this:

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

but what I get is this:

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

NOTE: I've asked a similar question, but it was NOT to build an associative array. Since it was not like I originally asked I figured another thread was required.

Community
  • 1
  • 1
Mike
  • 1,760
  • 5
  • 21
  • 40

1 Answers1

6

You can get this:

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

Code:

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; 
}
Sergey
  • 5,208
  • 25
  • 36
  • Apparently I need to give this coding crap up .. I spent 3 hours trying to get this on my own and you nailed it in less than 5 minutes. Awesome, thank you! – Mike Oct 22 '12 at 04:41