Create Array from Foreach - php

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.

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);
}

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);
}

Try this :
$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);
}
You were treating the cart as a variable instead of array

$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);
}
print_r($cart);

the way to approach this is first create a variable $cart = array();
and then do foreach();
i have written code below please go through it
foreach($data_main as $transaction_main){
$json_decoded = json_decoded($transaction_main);
$cart[]=array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
}

Related

Fill array with dynamic content in PHP

I need to fill an array with a dynamic list of products.
To do so, I'm using the following code:
$list_array = array(
$products[] = array(
'SKU' => '0001',
'Title' => 'Bread',
'Quantity' => '',
),
$products[] = array(
'SKU' => '0002',
'Title' => 'Butter',
'Quantity' => '',
)
);
return $list_array;
It works fine if I know every product in the array.
But in my use case I have no idea which products are in the array.
So I want to fill the array with dynamic data.
I came up with something this:
$products = get_posts( 'numberposts=-1&post_status=publish&post_type=product' );
foreach ( $products as $product ) {
$products[] = array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => '',
),
}
return $products;
I know there is something really wrong with the array. But I couldn't figure out what it is.
The code you submitted cannot work. The short syntax $a[] = ... is to append data to the $a array, for example:
$a = [];
$a[] = 1;
$a[] = 2;
// $a = [1, 2]
You can also do it in a more efficient way with a map function:
function reduce($product)
{
return array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => '',
);
}
return array_map('reduce', $products);
It will execute the function reduce and replace value for each element of you array. Complete doc here: https://www.php.net/manual/en/function.array-map.php
Your problem is that you are overwriting the $products array that you are looping over inside the loop. Change the name of the variable in the loop to fix that:
$list_array = array();
foreach ( $products as $product ) {
$list_array[] = array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => ''
);
}
return $list_array;

Last iteration values left in array

if ($cart = $this->cart->contents())
{
foreach ($cart as $item){
$order_detail = array(
'res_id' =>$this->session->userdata('menu_id[]'),
'customer_id' =>$coustomers,
'payment_id' =>$payment,
'name' => $item['name'],
'productid' => $item['id'],
'quantity' => $item['qty'],
'price' => $item['price'],
'subtotal' => $item['subtotal']
);
}
print_r($order_detail); exit;
when the foreach loop ends, only the last iteration value is left. I need all the values to be within the array.
Because order_detail will overwrite each time. Use array instead of simple variable.
$order_detail = array();
if ($cart = $this->cart->contents())
{
foreach ($cart as $item){
$order_detail[] = array(
'res_id' =>$this->session->userdata('menu_id[]'),
'customer_id' =>$coustomers,
'payment_id' =>$payment,
'name' => $item['name'],
'productid' => $item['id'],
'quantity' => $item['qty'],
'price' => $item['price'],
'subtotal' => $item['subtotal']
);
}
print_r($order_detail); exit;
Change this line
$order_detail = array(..);
to
$order_detail[] = array(..);
try this
first define the array
$order_detail=array();
array_push($order_detail, array(...));
array declaration must be outside the loop.

Looping through results of a sql query

I have a query that returns multiple rows. I can't seem to find a way to store the rows in the $params array. Is there a way to loop throw and store each row in the $params variable
$aResult = $db->exec_sql($sql);
$params = array(
// where $aResult[o]'' would be row 1 [1] row 2 etc. //
'store_id' => $aResult[]['iStoreID'],
'user_id' => $aResult[]['iUserID'],
'store_name' => $aResult[]['cStoreName'],
'store_url' => $aResult[]['cStoreURL'],
'rid' => $aResult[]['cRID'],
'affiliate_id' => $aResult[]['iAffiliateID'],
'team_id' => $aResult[]['iTeamID'],
'bizOP' => $aResult[]['cDefaultBizOpp'],
'showBizOPp' => $aResult[]['iShowBizOppDropdown'],
'boPosting' => $aResult[]['iEnableBOPosting'],
'brandinglevel' => $aResult[]['iBrandingLevel']
);
thank you for your help
As simple as that:
$params = array();
foreach($aResult as $row) {
$params[] = array(
'store_id' => $row['iStoreID'],
'user_id' => $row['iUserID'],
'store_name' => $row['cStoreName'],
'store_url' => $row['cStoreURL'],
'rid' => $row['cRID'],
'affiliate_id' => $row['iAffiliateID'],
'team_id' => $row['iTeamID'],
'bizOP' => $row['cDefaultBizOpp'],
'showBizOPp' => $row['iShowBizOppDropdown'],
'boPosting' => $row['iEnableBOPosting'],
'brandinglevel' => $row['iBrandingLevel']
);
}
Without knowing the exact structure of the result array i guess you need something like this:
<?php
$params = array();
$mapping = array(
'store_id' => 'iStoredID',
'user_id' => 'iUserID',
// and so on...
);
foreach ($aResult as $row) {
$tempRow = array();
foreach ($row as $key => $value) {
$paramKey = isset($mapping[$key]) ? $mapping[$key] : $key;
$tempRow[$paramKey] = $value;
}
$params[] = $tempRow;
}
I use it like this
$aResult = mysql_query($sql);
while($data = mysql_fetch_array($result)) {
'store_id' = $aResult['iStoreID'];
}
At least that is the idea

Create a MultiDimensional Array with PHP and Mysql Foreach Loops

I am needing to create a multidimensional array with sql and loops. However only one result gets set into the array, the last result is overwriting the previous results. Here is what the array structure looks like:
->value = Array (4)
CartID => "1299"
Date => "2012-09-27 09:17:20"
Amount => "85.00"
0 => Array (8)
CartStatus => "Purchased"
Date => "2012-09-27 09:17:20"
CartID => "1299"
Sequence => "1"
Amount => "-85.00"
Comments => " , Refund Status: "
Here is my code:
$txarray = array();
foreach ($data as $transaction) {
$CartVar = $transaction['CartID'];
$CartStatus = $transaction['Status'];
$CartDate = $transaction['DateTime'];
$CartTotal = $transaction['Total'];
$txarray = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);
$sql1 = $db->query("SQL stuff");
foreach ($sql1 as $refund) {
$CartID = $refund['CartID'];
$Sequence = $refund['Sequence'];
$TrxType = $refund['TrxType'];
$ParentID = $refund['ParentID'];
$TotalSum = '-'.$refund['Amount'];
$Comments = ' '.$refund['Comments'];
$Comments .= ', Refund Status: '.ucwords($refund['Status']);
$txarray[] = array('CartStatus' => $CartStatus, 'Date' => $CartDate, 'CartID' => $CartID, 'Sequence' => $Sequence, 'TrxType' => $TrxType, 'ParentID' => $ParentID, 'Amount' => $TotalSum, 'Comments' => $Comments);
}
Looking at above code snippet $txarray variable is overwritten due to code.
$txarray = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);
It needs to be replaced it with
$txarray[] = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);
or alternatively you can use array_push() function which will push arrays thereby resulting into multidimensional array.
e.g.
array_push($txarray,array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal));
For more documentation about array_push function please refer the documentation in below mentioned url.
http://php.net/manual/en/function.array-push.php
This line:
$txarray = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);
destroys any previous array'd you'd created in earlier iterations.

Check if an array of an array contains a certain string

I'm checking to make sure an array of arrays does not contain certain strings before adding any new child arrays to the parent array
I want to make sure that if an array with the same website and condition exists a new child array will not be added to the parent array.
e.g. in this example the $newArr must not be inserted in to the array $arr because their already exists an array with the same website and condition.
$arr = array(
array(
'website' => 'amazon',
'price' => 20,
'location' => 'uk',
'link' => '...',
'condition' => 'new'
),
array(
'website' => 'abe',
'price' => 20,
'location' => 'uk',
'link' => '...',
'condition' => 'new'
)
);
$newArr = array(
'website' => 'amazon',
'price' => 60,
'location' => 'uk',
'link' => '...',
'condition' => 'new'
)
I'm looking for an easy solution as using the function in_array on the parent array is not enough.
code so far
$arr = array();
foreach($table->find('tr.result') as $row){
if(($website = $row->find('a img',0))
&& ($price = $row->find('span.results-price a',0))
&& ($location = $row->find('.results-explanatory-text-Logo'))
&& ($link = $row->find('a',0))){
$website = str_replace( array('.gif','.jpg','.png'), '', basename($website->src));
$price = floatval(trim(str_replace(',', '', $price->innertext), "£"));
$location = "uk";
$link = $link->href;
$arr[] = array(
'website' => $website,
'price' => $price,
'location' => $location,
'link' => $link,
'condition' => 'new'
);
}
}
You loop over $arr each time to look for $website and $condition (always 'new'?) or you can keep a secondary array of the found keys. If you're starting with an empty $arr each time, the second approach will work and be faster.
$arr = array();
$keys = array();
foreach($table->find('tr.result') as $row){
if(...){
...
$condition = 'new'; // set as needed
// track seen keys
$key = $website . '|' . $condition; // assumes neither field contains '|'
if (!isset($keys[$key])) {
$keys[$key] = true;
$arr[] = array(...);
}
}
}
I hope the comments in the below code speak for themselves... I'm not a PHP pro, and this is probably not the most elegant way, but I believe the logic makes sense. Obviously the $new_array object has some variables that aren't declared but it's for example only.
I hope that helps and that no one down votes me :)
<?php
// Original array
$arr = array();
foreach($result as $row) {
// Get the new array as an object first so we can check whether to add to the loop
$new_array = array(
'website' => $website,
'price' => $price,
'location' => $location,
'link' => $link,
'condition' => 'new'
);
// If the original array is empty there's no point in looping through it
if(!empty($arr)) {
foreach($arr as $child) {
// Check through each item of the original array
foreach($new_array as $compare) {
// Compare each item in the new array against the original array
if(in_array($compare, $child)) {
// if there's a match, the new array will not get added
continue;
}
}
}
}
// If there's no match, the new array gets added
$arr[] = $new_array;
}
?>

Categories