I have an the variable $users
set to an array that resembles the below
Array(
[4] => Array(
[userid] => 4
[name] => Mike
[gender] => M
)
[5] => Array(
[userid] => 5
[name] => Sally
[gender] => F
)
[6] => Array(
[userid] => 6
[name] => Steve
[gender] => M
)
)
I then have code that loops through this array to call a function to calculate age.
foreach($users as $user){
$age = getUserAge($user->id);
}
How do I take the variable $age
and add it into $users
to result with the follow array?
Array(
[4] => Array(
[userid] => 4
[name] => Mike
[gender] => M
[age] => 35
)
[5] => Array(
[userid] => 5
[name] => Sally
[gender] => F
[age] => 24
)
[6] => Array(
[userid] => 6
[name] => Steve
[gender] => M
[age] => 32
)
)
To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.
Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.
Change Array Key using JSON encode/decode It's short but be careful while using it. Use only to change key when you're sure that your array doesn't contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.
foreach($users as &$user){
$age = getUserAge($user['userid']);
$user['age'] = $age;
}
Compact Version:
foreach($users as &$user){
$user['age'] = getUserAge($user['userid']);
}
Note the ampersand before the array variable name meaning the variable is passed by reference, and so can be modified. See the docs for more info.
foreach($users as $index => $user) {
$users[$index]['age'] = getUserAge($user['userid']);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With