0

I have a list of categories in MySQL with parent ID. How can I create a PHP array from the list.

ID  Category      Parent_ID
1   Car           NULL
2   Education     NULL
3   Mathematics   2
4   Physics       2
5   Astrophysics  4

I want to produce an array of this structure

array(
    "Car" => "1",
    "Education" => array("Mathematics" => "2", "Physics" => array("Astrophysics" => "4"))
);

As a matter of fact, key/value is not important as I will work with other columns too. I just want to know how to scan the list and produce multi-level list.

2
  • 2
    what s your key to array? how do you want your array to look? do you want assoc. array? or you want to store each row as an object? Commented Oct 25, 2011 at 3:24
  • I added a sample array to the question :) Commented Oct 25, 2011 at 3:32

1 Answer 1

5

Some very simple recursion to build a tree structure:

function buildTree(array $data, $parent = null) {
    $branch = array();

    foreach ($data as $row) {
        if ($row['parent_id'] == $parent) {
            $row['children'] = buildTree($data, $row['id']);
            $branch[] = $row;
        }
    }

    return $branch;
}

$tree = buildTree($rowsFromDatabase);

Having an explicit 'children' key is usually preferable to the structure you're proposing, but feel free to modify as needed.

Sign up to request clarification or add additional context in comments.

3 Comments

$parent = null should be $parent = "" mysql returns empty string for null values. Other than that +1.
@Louis You're right. It'll still work correctly though, since we're only comparing loosely. :)
@deceze You can do this with one loop only, no need for n*n loops. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.