Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Array from Foreach

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.

like image 249
Matthew Colley Avatar asked Feb 15 '12 13:02

Matthew Colley


2 Answers

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);
    }
like image 121
NDBoost Avatar answered Oct 02 '22 13:10

NDBoost


Your variable $cart is being overwritten in each loop because you are calling array() each time.

Instead, declare your array outside the loop, and just add values to it as needed:

$cart = 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);
}
like image 31
George Cummins Avatar answered Oct 02 '22 13:10

George Cummins