Search code examples
phparraysforeach

Loop only puts last iteration into array, but should have multiple rows


I have a Mysql table which contains a column of JSON data and a column with an amount. The goal is to extract the JSON data and the amount and build an array within the foreach loop. Here is my code:

$sql = "SELECT `Amount`, `NewObject` FROM `mb_cart` WHERE `MyID` = '$id'";
$data_main = $db->query($sql);

Here is my statement that I am using to build the array:

foreach ($data_main as $transaction_main) {
    $json_decoded = json_decode($transaction_main);
    $cart = array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
}

However when I run this, I am only returning only the first record set and the amount is blank, but the JSON data is listed. Appreciate any insight anyone cares to share.


Solution

  • You need to add [] to $cart array. WIth each run of foreach you're overwriting the variable $cart.

    something like so would work:

    foreach ($data_main as $transaction_main) {
        $json_decoded = json_decode($transaction_main);
            $cart[] = array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
        }
    

    Or if you wanted the array key to match that of the ID of each row:

    Note: You will need to set $id variable somehow above IE: SELECT id, amount also note that you COULD potentially have issues if integer from id is non-unique.. eg(1,1,2,3,4,5,6) it will only show the last id of 1 instead of both (since key's are duplicates).

    foreach ($data_main as $transaction_main) {
        $json_decoded = json_decode($transaction_main);
            $cart[$id] = array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
        }