I just want some help in displaying the correct structure of the image data below. Basically what i want is to display it in nested form. From the data below, I would like it to display like this:
I hope anyone can help me. Im using php fyi.
Do it recursively
// For example, data fetched from database:
$data = [
['id' => 1, 'sku' => 'name1', 'parent_id' => null],
['id' => 2, 'sku' => 'name12', 'parent_id' => 1],
['id' => 3, 'sku' => 'name12', 'parent_id' => 1],
['id' => 4, 'sku' => 'name2', 'parent_id' => null],
['id' => 5, 'sku' => 'name123', 'parent_id' => 2],
];
// Recursive function
function outTree($data, $parentId = null) {
$str = '';
foreach ($data as $row) {
if ($row['parent_id'] == $parentId) {
$str .= '<li>' . $row['sku'];
$str .= outTree($data, $row['id']);
$str .= '</li>';
}
}
if ($str) {
$str = '<ul>' . $str . '</ul>';
}
return $str;
}
echo outTree($data);