2

I'm within a foreach loop and I'd like to add multiple values to an array

$allcustomers = array();
foreach ($customers as $entry) {
  $allcustomers['User Email'] = $user_meta['0']['user_email'];
  $allcustomers['Customer ID'] = $customer_id;
}

This is what it's outputting:

Array
(
    [User Email] => [email protected]
    [Customer ID] => 18060
)

So it's just overwriting the one array constantly. I want it to output the same but for every customer.

How do I create an array for each loop?


Array
(
    [0] => Array
        (
            [User Email] => [email protected]
            [Customer ID] => 184
        )

    [1] => Array
        (
            [User Email] => [email protected]
            [Customer ID] => 185
        )

    [2] => Array
        (
            [User Email] => [email protected]
            [Customer ID] => 183
        )

3 Answers 3

3
$allcustomers = array();
foreach ($customers as $entry) {
    $allcustomers[] = [
        'User Email' => $user_meta['0']['user_email'],
        'Customer ID' => $customer_id,
    ];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Nope. What's the problem with subarrays?
But your initial code creates array with data sitting on top level, no?
0

Try like this. If you want different array of User Email and Customer ID

$allcustomers = array();
    foreach ($customers as $entry) {
      $allcustomers['User Email'][] = $user_meta['0']['user_email'];
      $allcustomers['Customer ID'][] = $customer_id;
    }

Or you want in same array then.

$allcustomers = array();
foreach ($customers as $entry) {
    $allcustomers[] = [
        'User Email' => $user_meta['0']['user_email'],
        'Customer ID' => $customer_id,
    ];
}

Comments

0

Try this:

foreach($customers as $user_meta){
allValues[] = [
    'User Email' => $user_meta['0']['user_email'],
    'Customer ID' => $customer_id
];}

Where did you set customer_id? I think you need to get it from the user meta too.

Best regards

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.