Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push associative array from for-loop in php

The for loop is supposed to loop 10 times. When I just print the $fname, $lname and $email I am getting the 10 data (Working fine)

But I need to store those value in an associative array.

$assocDataArray = array();
foreach ($data as $key => $value) {
    foreach ($value['emails'] as $lead) {
        $fname = $lead['first_name'];
        $lname = $lead['last_name'];
        $email = $lead['value'];

        //put objects in array
        $assocDataArray += [ "First Name" => $fname ];
        $assocDataArray += [ "Last Name" => $lname ];
        $assocDataArray += [ "Email" => $email ];
    }
}

var_dump($assocDataArray);

var_dump is only giving me one array [Expected 10]

like image 653
Saurabh Avatar asked Mar 07 '23 04:03

Saurabh


2 Answers

This assignment:-

$assocDataArray += [ "First Name" => $fname ];
$assocDataArray += [ "Last Name" => $lname ];
$assocDataArray += [ "Email" => $email ];

Is wrong.Change it like below

$assocDataArray[] = [ "First Name" => $fname ,"Last Name" => $lname ,"Email" => $email ];
like image 62
Anant Kumar Singh Avatar answered Mar 11 '23 19:03

Anant Kumar Singh


You can assign the key

$assocDataArray = array();
foreach ($data as $key => $value) {
    foreach ($value['emails'] as $lead) {
        $fname = $lead['first_name'];
        $lname = $lead['last_name'];
        $email = $lead['value'];

        //put objects in array
        $assocDataArray[ $key ]['First Name'] = $fname;
        $assocDataArray[ $key ]['Last Name'] = $lname;
        $assocDataArray[ $key ]['Email'] = $email;
    }
}

var_dump($assocDataArray);

```

like image 33
Faytraneozter Avatar answered Mar 11 '23 17:03

Faytraneozter