Skip to content

Instantly share code, notes, and snippets.

@dikiwidia
Created June 20, 2022 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dikiwidia/9c2b4e72fd879c0646cabdaf77f75eb2 to your computer and use it in GitHub Desktop.
Save dikiwidia/9c2b4e72fd879c0646cabdaf77f75eb2 to your computer and use it in GitHub Desktop.
Looping Problem Sequence Tree
<?php
$datas = [
['id'=> 1, 'parent_id' => 0, 'type' => 'HEADER', 'sequence_no' => 1],
['id'=> 2, 'parent_id' => 1, 'type' => 'OTHER', 'sequence_no' => 2],
['id'=> 3, 'parent_id' => 1, 'type' => 'OTHER', 'sequence_no' => 3],
['id'=> 4, 'parent_id' => 0, 'type' => 'HEADER', 'sequence_no' => 4],
['id'=> 5, 'parent_id' => 4, 'type' => 'OTHER', 'sequence_no' => 5],
['id'=> 6, 'parent_id' => 4, 'type' => 'OTHER', 'sequence_no' => 6],
['id'=> 7, 'parent_id' => 0, 'type' => 'HEADER', 'sequence_no' => 7],
['id'=> 8, 'parent_id' => 7, 'type' => 'OTHER', 'sequence_no' => 8],
];
$datas_new = [];
$header_no = 1;
foreach ($datas as $data) {
if ($data['type'] == 'HEADER'){
$data['sequence_no'] = $header_no++;
array_push($datas_new, $data);
$child_no = 1;
} else {
$data['sequence_no'] = $child_no++;
array_push($datas_new, $data);
}
}
echo "<pre>";
print_r($datas_new);
echo "</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment