note 124521 added to function.array-merge
| From: | souzacomprog at gmail dot com | Date: | Wed, 18 Dec 2019 23:42:31 +0000 |
| Subject: | note 124521 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-213554@lists.php.net to get a copy of this message | ||
Sometimes we need to traverse an array and group / merge the indexes so that it is easier to extract
them so that they are related in the iteration.
<?php
$people = [
['id' => 1, 'name' => 'Hayley'],
['id' => 2, 'name' => 'Jack', 'dad' => 1],
['id' => 3, 'name' => 'Linus', 'dad' => 4],
['id' => 4, 'name' => 'Peter'],
['id' => 5, 'name' => 'Tom', 'dad' => 4],
];
// We set up an array with just the children
function children($dad, $people)
{
$children = [];
foreach ($people as $p) {
if (!empty($p["dad"]) && $p["dad"] == $dad["id"]) {
$children[] = $p;
}
}
return $children;
}
$family = [];
// We merge each child with its respective parent
foreach ($people as $p) {
$children = children($p, $people);
if ($children != []) {
$family[] = array_merge($p, ["children" => $children]);
}
}
print_r($family);
?>
//OUTPUT
Array
(
[0] => Array
(
[id] => 1
[name] => Hayley
[children] => Array
(
[0] => Array
(
[id] => 2
[name] => Jack
[dad] => 1
)
)
)
[1] => Array
(
[id] => 4
[name] => Peter
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => Linus
[dad] => 4
)
[1] => Array
(
[id] => 5
[name] => Tom
[dad] => 4
)
)
)
)
----
Server IP: 45.112.84.4
Probable Submitter: 38.142.137.34 (proxied: 138.36.205.232)
----
Manual Page -- http://php.net/manual/en/function.array-merge.php
Edit -- https://master.php.net/note/edit/124521
Del: integrated -- https://master.php.net/note/delete/124521/integrated
Del: useless -- https://master.php.net/note/delete/124521/useless
Del: bad code -- https://master.php.net/note/delete/124521/bad+code
Del: spam -- https://master.php.net/note/delete/124521/spam
Del: non-english -- https://master.php.net/note/delete/124521/non-english
Del: in docs -- https://master.php.net/note/delete/124521/in+docs
Del: other reasons-- https://master.php.net/note/delete/124521
Reject -- https://master.php.net/note/reject/124521
Search -- https://master.php.net/manage/user-notes.php