Reputation: 589
I'm using CakePHP and retrieve user info, make a calculation, and then I'd like to add that calculation into the array per user
After looking up a user, this is the structure of the array
print_r($user_info);
Array
(
[0] => Array
(
[User] => Array
(
[id] => 1
[email] => [email protected]
[website] => www.admin.com
)
)
)
Now I'm trying to add a 'num_payments' key for this particular user in a loop
array_push($user_info[$i]['User'],array('num_payments' => $customer_payments[$i]['num_payments']));
Here's the resulting array
Array
(
[0] => Array
(
[User] => Array
(
[id] => 1
[email] => [email protected]
[website] => www.admin.com
[0] => Array
(
[num_payments] => 1
)
)
)
)
How can I get it into this structure?
Array
(
[0] => Array
(
[User] => Array
(
[id] => 1
[email] => [email protected]
[website] => www.admin.com
[num_payments] => 1
)
)
)
Upvotes: 1
Views: 2636
Reputation: 11574
It sounds like you should add a join
to your query to pull in the data combined with the user data. Then you can use the Hash::combine
method to merge the data into the array it belongs to.
However, if you are just running a loop on the data, you should be able to add it like:
foreach ($user_info as $i -> $data) {
$user_info[$i]['User']['num_payments'] = $customer_payments[$i]['num_payments'];
}
This is assuming that $i
corresponds to the same record in both arrays.
If $i
in $customer_payments
corresponds to the User.id
, then it will require that you do this:
foreach ($user_info as $i -> $data) {
$user_info[$i]['User']['num_payments'] = $customer_payments[$user_info[$i]['User']['id']]['num_payments'];
}
Upvotes: 1
Reputation: 70863
$user_info[$i]['User']['num_payments'] = $customer_payments[$i]['num_payments'];
Upvotes: 1
Reputation: 1985
without array_push
:
$user_info[$i]['User']['num_payments'] = $customer_payments[$i]['num_payments'];
Upvotes: 3