From the query in the database you need to form an embedded array. Table Fields: id, text, id_parent Array structure

Attempts to solve:

while($row = mysql_fetch_object($result)){ if($row->id_parent){ $mas[$row->id_parent]['children'][$row->id]['id'] = $row->id; $mas[$row->id_parent]['children'][$row->id]['text'] = $row->text; $mas[$row->id_parent]['children'][$row->id]['id_parent'] = $row->id_parent; }else{ $mas[$row->id]['id'] = $row->id; $mas[$row->id]['text'] = $row->text; $mas[$row->id]['id_parent'] = $row->id_parent; } 

Closed due to the fact that the essence of the question is incomprehensible to the participants user31688, VenZell , user26699, dizballanze , Abyx 1 Jun '15 at 13:41 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • AND? The question is what? - user31688
  • Actually how to form an array of this type? - Artem Y
  • Take out the data and form, what's the problem then? - user31688
  • the problem is that when forming the array, I don’t know what level of parenting is in - Artem Y
  • Bring your decision attempts. Plus - I doubt that doing a multi-level array is such a good idea. It is quite possible to do one or two dimensional in 99%. - user31688

2 answers 2

 function buildTree(array $data, $id = 'node_id', $parent = 'parent_id', $children = 'children') { if (empty($id) || empty($parent) || empty($children)) { throw new \InvalidArgumentException; } $tree = $refs = []; foreach ($data as &$node) { $refs[$node[$id]] = &$node; $node[$children] = []; if (null === ($node[$parent])) { $tree[$node[$id]] = &$node; } else { $refs[$node[$parent]][$children][$node[$id]] = &$node; } } return $tree; } 
      function buildTreeArray($arItems, $section_id = 'Ид_родителя', $element_id = 'Ид') { $childs = array(); if(!is_array($arItems) || empty($arItems)) { return array(); } foreach($arItems as &$item) { if(!$item[$section_id]) { $item[$section_id] = 0; } $childs[$item[$section_id]][] = &$item; } unset($item); foreach($arItems as &$item) { if (isset($childs[$item[$element_id]])) { $item['childs'] = $childs[$item[$element_id]]; } } return $childs[0]; }