note 124521 deleted from function.array-merge by salathe

From: Date: Mon, 06 Sep 2021 22:47:45 +0000
Subject: note 124521 deleted from function.array-merge by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-216913@lists.php.net to get a copy of this message
Note Submitter: souzacomprog at gmail dot com ---- 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 ) ) ) )

« previous php.notes (#216913) next »