I am using https://github.com/dbushell/Nestable library.
Everything works fine using the library but I want to validate the request as an extra protection to avoid infinite loop if someone will force the request manually (hypothetical).
I was wondering if someone knows an elegant way to get this without doing another recursive function to check if the parent becomes a child at some point.
Example:
$data = [
[
"id" => 1,
],
[
*"id" => 2,*
"children" => [
[
"id" => 3,
],
[
"id" => 4,
],
[
"id" => 5,
"children" => [
[
"id" => 6,
],
[
"id" => 7,
],
[
"id" => 8,
"children" => [
[
*"id" => 2,*
],
[
"id" => 10,
],
],
],
],
],
[
"id" => 11,
],
[
"id" => 12,
],
],
],
[
"id" => 13,
],
[
"id" => 14,
],
];
nestableLinks($data);
/**
* Nestable links.
*
* @param $links
* @param null $parent_id
* @param int $weight
*/
function nestableLinks($links, $parent_id = NULL, $weight = 0)
{
foreach ($links as $link) {
$weight++;
var_dump(['id' => $link['id'], 'parent_id' => $parent_id, 'weight' => $weight]);
if (array_key_exists('children', $link)) {
nestableLinks($link['children'], $link['id']);
}
}
}