Skip to content
Advertisement

PHP assign parent ids for children in array

I’am stuck on assigning pid’s (parent id’s) on 3rd element. I mean in setParent() if I return $array before call recursive function, then I see that “PC” and “Laptop” are having correct pid’s. If I run all script, then I get $newArr is null. PHP 7.3, Laravel 6.

I want to make this:

JavaScript

From that :

JavaScript

Advertisement

Answer

You could build hierarchy paths for each of your entries using implode, then make use of array_reduce to:

  • index your entries by their path,
  • alter the pid of each subsequent entry if their parent’s path was found.

Finally, array_values will switch back your array’s indexes to numerical format.

Note: this assumes the parents are always defined before their children, like in your sample data.

Note 2: this also assumes the names such as 'pc' cannot contain forward slashes (/). Feel free to change the separator otherwise.

JavaScript

Usage:

JavaScript

Demo: https://3v4l.org/DeORi

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement