I need to push a new property into my array of arrays of objects using the values from a flat array.
My sample arrays:
$users = [ [ (object) ["user_id" => 2] ], [ (object) ["user_id" => 1], (object) ["user_id" => 1], ], [ (object) ["user_id" => 2], (object) ["user_id" => 2] ] ]; $is_admin = [ false, true, true, false, false ];
I need to write is_admin => [boolean value]
(one at a time) into each object using the values from the second array.
Desired result:
[ [ (object) ["user_id" => 2, "is_admin" => false] ], [ (object) ["user_id" => 1, "is_admin" => true], (object) ["user_id" => 1, "is_admin" => true], ], [ (object) ["user_id" => 2, "is_admin" => false], (object) ["user_id" => 2, "is_admin" => false] ] ]
I do not know how to map the second array with the first array’s structure. I have tried using array_merge
, but it doesn’t work properly with my data structure and requirements.
Advertisement
Answer
You can use array_walk_recursive
function:
array_walk_recursive($users, function (&$user) use (&$is_admin) { $user->is_admin = current($is_admin); next($is_admin); });
Pay attention that both $user
and $is_admin
passed by reference.
Also, you can use outer index variable (i.e. $i
) to track $is_admin
position. In such case, you need to pass (to be more precise enclose) $i
along side with $is_admin
, only $i
will be passed by reference and $is_admin
by value. I decided to take advantage of current
and next
functions, not introducing one more variable.
Here is working demo.
One important thing. If your $is_admin
array has fewer elements than $users
arrays (they are leaves actually) false
value will be assigned to the is_admin
field of those users that comes after the point when there are no elements left in $is_admin
.