John Davidson

php - Group array of objects into deeper parent-child structure

0 comments
Message:


My input data is an array of objects. I need to restructure these objects so that an object with value = 0 becomes a "parent" object with a subarray which will collect all subsequent objects until another "parent" object is encountered.


Sample array:


    $array = [
(object) ['id'=> 1, 'value' => 0],
(object) ['id'=> 2, 'value' => 10],
(object) ['id'=> 3, 'value' => 14],
(object) ['id'=> 4, 'value' => 0],
(object) ['id'=> 5, 'value' => 21],
(object) ['id'=> 6, 'value' => 44],
];

The desired result:


    [
(object) [
'id' => 1,
'value' => 0,
'values' => [
(object) ['id' => 2, 'value' => 10],
(object) ['id' => 3, 'value' => 14],
],
],
(object) [
'id' => 4,
'value' => 0,
'values' => [
(object) ['id' => 5, 'value' => 21],
(object) ['id' => 6, 'value' => 44],
]
]
]

I'm struggling to make a start. Should I approach this with a foreach?


foreach ($array as $item) {
// What to do?
}



My Answer:
parent object, and objects with value > 0 become children of the parent object.

Here is an example of the input data:

php
$input = [
(object) ['id' => 1, 'value' => 0],
(object) ['id' => 2, 'value' => 1],
(object) ['id' => 3, 'value' => 2],
(object) ['id' => 4, 'value' => 0],
(object) ['id' => 5, 'value' => 3],
(object) ['id' => 6, 'value' => 0],
(object) ['id' => 7, 'value' => 4],
];


To group these objects into a parent-child structure, we can use the following code:

php
$output = [];
$parent = null;

foreach ($input as $obj) {
if ($obj->value == 0) {
$parent = $obj;
$output[] = $parent;
} else {
$parent->children[] = $obj;
}
}

print_r($output);


This code will output the following structure:


Array
(
[0] => stdClass Object
(
[id] => 1
[value] => 0
[children] => Array
(
[0] => stdClass Object
(
[id] => 2
[value] => 1
)

[1] => stdClass Object
(
[id] => 4
[value] => 0
[children] => Array
(
[0] => stdClass Object
(
[id] => 5
[value] => 3
)

)

)

[2] => stdClass Object
(
[id] => 6
[value] => 0
[children] => Array
(
[0] => stdClass Object
(
[id] => 7
[value] => 4
)

)

)

)

)

)


In this structure, objects with value = 0 are parent objects, and objects with value > 0 are children of their respective parent objects.

Rate this post

5 of 5 based on 7680 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us