1

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
                )

        )

)

3 Answers 3

3

without array_push:

$user_info[$i]['User']['num_payments'] = $customer_payments[$i]['num_payments'];
Sign up to request clarification or add additional context in comments.

2 Comments

So just loop through the values?
Wow, that was painfully obvious. Time to step away from the keyboard. Thanks!
1
$user_info[$i]['User']['num_payments'] = $customer_payments[$i]['num_payments'];

Comments

1

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'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.