Answer the question
In order to leave comments, you need to log in
PHP. How to form a dynamic multidimensional array?
The database has a category table. Categories have a hierarchical structure. Displaying them in the form of a tree with echo-m li-shkas is easy (I do it using recursion). But here's how to form a multidimensional array?
UPD
Example.
There is a large diameter pipeline:
id | parent_id
2 | 1
3 | 1
4 | 2
5 | 2
The output should be such an array (I convey the meaning itself, you can of course arrange it differently, for example, use the 'childs' subarrays, and also take into account the root category in the real code):
$array = [
0=>[
'node'=>1,
0=>['node'=>2, 0=>4, 1=>5],
1=>3,
],
];
Answer the question
In order to leave comments, you need to log in
Without using links, the tree is built like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('xdebug.var_display_max_depth', -1);
$items = [
['id' => 1, 'name' => 'A', 'parent' => 0],
['id' => 2, 'name' => 'A-1', 'parent' => 1],
['id' => 3, 'name' => 'A-1-1', 'parent' => 2],
['id' => 5, 'name' => 'A-1-1-2', 'parent' => 3],
['id' => 6, 'name' => 'A-2', 'parent' => 1],
['id' => 7, 'name' => 'A-2-2-1', 'parent' => 6],
['id' => 4, 'name' => 'A-1-1-1', 'parent' => 3],
['id' => 8, 'name' => 'A-2-2-2', 'parent' => 6],
['id' => 9, 'name' => 'A-2-2-1-1', 'parent' => 7],
['id' => 10,'name' => 'B', 'parent' => 0],
];
function buildTree(array $items, $parent = 0)
{
$tree = array();
foreach ($items as $item) {
if ($item['parent'] === $parent) {
$children = buildTree($items, $item['id']);
if ($children) {
$item['children'] = $children;
}
$tree[] = $item;
}
}
return $tree;
}
function getList($items = [])
{
$html = '';
foreach ($items as $item) {
$html .= vsprintf('<ul><li><span>%s</span>%s</li></ul>', [
$item['name'],
empty($item['children']) ? '' : getList($item['children'])
]);
}
return $html;
}
$tree = buildTree($items);
$list = getList($tree);
echo "<pre>";
echo $list;
var_dump($tree);
echo "</pre>";
exit("File: " . __FILE__ . " Line: " . __LINE__);
More or less like this:
$sql = 'SELECT * FROM `categories`';
$stmt = DBH::PDO()->query($sql)->execute();
$data = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC){
$data[$row['parent']][$row['id']] = $row;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question