Klav Klav - 5 months ago 21
PHP Question

How to correctly populate Array from While Loop PHP

I'm populating an Array from a While Loop but am unable to produce the proper array format. I've hit many different variations but not what I am looking for which is included below. The purpose is for 3rd party SMTP, as seen in the variable

$to


Desired Array:

array(3) {
["email1@email1.com"]=> array(1) { ["userid"]=> string(1) "6" }
["email2@email2.com"]=> array(1) { ["userid"]=> string(2) "64" }
["email3@email3.com"]=> array(1) { ["userid"]=> string(3) "503" }
}


Attempt 1:

$str = array();
while($userEmails = $query->fetch(PDO::FETCH_ASSOC)){

$str[] = '"'.$userEmails['user_email'].'" => array(
"userid" => "'.$userEmails['user_id'].'"
)';
}
$to = $str;


Attempt 1 Incorrect Array:

array(3) {
[0]=> string(54) ""email1@email1.com" => array( "userid" => "6" )"
[1]=> string(54) ""email2@email2.com" => array( "userid" => "64" )"
[2]=> string(54) ""email3@email3.com" => array( "userid" => "503" )"
}


Attempt 2:

$str = "";
while($userEmails = $query->fetch(PDO::FETCH_ASSOC)){

$str .= '"'.$userEmails['user_email'].'" => array( "userid" => "'.$userEmails['user_id'].'" )';
}

$emails = rtrim($str, ", ");

$to = array($emails);


Attempt 2 Incorrect Array:

array(1) {
[0]=> string(162) ""email1@email1.com" => array( "userid" => "6" )"email2@email2.com" => array( "userid" => "64" )"email3@email3.com" => array( "userid" => "503" )" }

Answer

You want this, I think:

$str = array();
while($userEmails = $query->fetch(PDO::FETCH_ASSOC)){
    $str[$userEmails['user_email']] = array(
        'user_id' => $userEmails['user_id']
    );
}
Comments