Search code examples
phparraysrecursionresultset

make a nameless array out 2 diferent tables with children in php


I have 2 tables in my DB. 1 is full with numbers (foreign keys) and other one is full of the data I need. This is how the array should (exactly) look

"array" : [
    {
        "data" : "blabla"
        "data2" : "blabla"
        "children" : [
            {
                "data" : "blabla"
                "data2" : "blabla" 
                "children" : [
                    {
                        "data" : "blabla"
                        "data2" : "blabla" 
                    }
                ]
            },
            {
                "data" : "blabla"
                "data2" : "blabla" 
                "children" : [
                    {
                        "data" : "blabla"
                        "data2" : "blabla" 
                    }
                ]
            }
        ]
    }
]

and so on, so to say.. now the right order you can find in table 1,where it is lited what the mother ID is. and i need to get the data out of table 2 so be in the array. anyone knows how to do this? i am working in codeigniter

updated with pics:

enter image description here

enter image description here


Solution

  • To do that, you would need to process in two steps:

    1. You fetch each document and it's data from the two tables (let's call them "documents" and "documents_data" to build a flat array of all the documents. This way you don't have to wonder where does the data go anymore :

      $results = $this->db->query("SELECT d.*, dd.* FROM documents d LEFT JOIN documents_data dd ON dd.doc_id = d.doc_id");
      $documents = $results->result_array();
      
    2. Now that we have everything about each document, we just need to reorder them in a recursive array using a recursive function, that will call itself with the parent id for each children and build the tree :

      function getDocumentTree($documents, $idParent = null)
      {
          $tree = [];
      
          foreach($documents as $document) {
              if($document['doc_doc_id'] == $idParent) {
                  $document['children'] = getDocumentTree($documents, $document['doc_id']);
                  $tree[] = $document;
              }
          }
      
          return $tree;
      }
      
      $tree = getDocumentTree($documents);
      

    Note: I haven't tested this code, this is just an idea on how it works, try to understand that (especially the concept of recursivity) and implement it by yourself.