MySQL/PHP code to get all parent id’s and their children in an array
  • While I was working on a project for our travel website, Carefreetrip.com Travel, I was faced with the need to develop a MySQL query using PHP that would allow me to pull a group of database objects that were in flat form and group them into an array by parent id’s and associated children, grandchildren, great grandchildren, etc., etc. (you get the idea) objects.

    After going through the several options and lots of Googling, I discovered a way to pull the parent_id from the database, put the parent_id into one array and then put all of the children objects into a second array. Here is the code that I used -

    $parent_refs = array();
    $child_list = array();
    $result = mysql_query(“SELECT item_id, parent_id, title FROM your_database ORDER BY item_name”);
    while($data = @mysql_fetch_assoc($result)) {

    $thisitem = &$parent_refs[ $data['id'] ];

    $thisitem['parent_id'] = $data['parent_id'];
    $thisitem['title'] = $data['title'];
    $thisitem['id'] = $data['id'];

    if ($data['parent_id'] == $thisitem) {
    $child_list[ $data['id'] ] = &$thisitem;
    } else {
    $parent_refs[ $data['parent_id'] ][ $data['id'] ] = &$thisitem;
    }

    }

    Basically this allows you to pull all of the items from “your_database”, assign the parents to one array ($parent_refs), while looping those items with corresponding parent_id’s and add them to a second array ($child_list) creating a multidimensional array.

    You can view the results by using PHP’s print_r function or “print_r($child_list)” to view the multidimensional array.  I hope this helps someone!

     


    November 7th, 2012 | Kyle Henrie | No Comments |

About The Author

Kyle Henrie

Kyle has over 16 years of experience in all phases of creating and executing marketing, promotions, public communications, technical development and project management designed to increase business growth.

Leave a Reply

* Name, Email, and Comment are Required