Basically iv getting a list or orders, then a list of items associated with that user.
This is my code
$collection_array = array();
$collection_items_array = array();
foreach($getCollections as $k => $collection){
$collection_array['CustomerAccountID'] = $collection['collection_account_id'];
$collection_array['TotalCount'] = $collection['totalCount'];
// Get order items
$get_order_items = $Collection->getItems($collection['collection_account_id']);
foreach($get_order_items as $i => $items){
$collection_items_array['OrderID'] = $items['order_id'];
$collection_items_array['OrderItemID'] = $items['item_id'];
$cia[] = $collection_items_array;
}
$collection_array['CollectionItems'] = $cia;
$ca[] = $collection_array;
}
but when i echo this out, its showing all the correct results for the results but then it shows the seconds results + the results...
Related
So I've been trying with this for a while now and can't seem to find the solution.
I have a website, selling digital good.
When the client checks out, it asks for what quantity.
I want to make it so when they type in for example, quantity 5, I want it to grab 5 stocks from the database and send all to their email.
I need to make it loop through and grab x quantity from a stock table where the assignedProduct is the product ID.
Currently, my code only getting the number of quantity and not getting different rows from my stock database. How do I make it loop the stock?
My current code is (using blockchain payment processor):
<?php
$smtp_btc = $pdo->prepare('SELECT * FROM `productitems` WHERE `avaliable` = :avaliable AND `assignedProduct` = :assignedProduct');
$smtp_btc->execute(array(':avaliable' => '0', ':assignedProduct' => $product_id));
$query = $smtp_btc->fetchAll();
// Select all from stock where avaliable = true and assignedProduct is the main productID
// Then make it
// Foreach loop here
$i = 0;
$maxiterations = $quantity - 1;
$message = '';
foreach($query as $row_product) {
while($i <= $maxiterations) {
$i++;
$product_link_stock = $row_product['code'];
$stock_id_stock = $row_product['id'];
$message = "<tr style='background: #eee;'><td><strong>Email/Username:Pass(".$i."):</strong> </td><td>$product_link_stock</td></tr>";
echo $message.'<br>';
}
}
?>
You have two loops, a foreach loop and a while loop. The data is being set once in the outer foreach loop, apparently to the first line of the query result or there may only be one result.
And then you're just printing the same data 3 times from the while loop.
Going up to the top:
$query = $smtp_btc->fetchAll();
What is the actual contents of $query here? Is it just 1 record?
So it turns out I need to do my query inside of my while loop so it can change the row it selects for each quantity.
This is my working code:
$i = 1;
$maxiterations = $quantity;
while($i <= $maxiterations) {
$smtp_btc = $pdo->prepare("SELECT * FROM `productitems` WHERE `avaliable` = :avaliable AND `assignedProduct` = :assignedProduct LIMIT $maxiterations");
$smtp_btc->execute(array(':avaliable' => '0', ':assignedProduct' => $product_id));
$query = $smtp_btc->fetchAll();
foreach($query as $row_product) {
$product_link_stock = $row_product['code'];
$stock_id_stock = $row_product['id'];
$message .= "<tr style='background: #eee;'><td><strong>Email/Username:Pass(".$i."):</strong> </td><td>$product_link_stock</td></tr>";
// Update stock foreach stock product they require (quantity depends on this)
$updateStock = $pdo->prepare('UPDATE `productitems` SET `avaliable` = :avaliable WHERE `id` = :id');
$updateStock->execute(array(':avaliable' => '1', ':id' => $stock_id_stock));
$i++;
}
$i++;
}
I currently have an array that is building with the correct data by looping an object but it's giving the incorrect format:
$priceResult = array();
foreach($prices->categories as $category){
$priceResult[] = $category->category_name;
$priceResult[] = $category->category_desc;
$priceResult[] = $category->category_code;
foreach($category->products as $product){
$priceResult[] = $product->product_info->item->item_code;
foreach ($product->product_info->details as $details) {
$priceResult[] = $details->description;
$priceResult[] = $details->color;
$priceResult[] = $details->sector;
}
$priceResult[] = $product->product_info->code;
$priceResult[] = $product->product_info->item->description;
$priceResult[] = $product->product_info->item->item_type->quantity;
foreach(get_object_vars($product->prices) as $amount){
$priceResult[] = $amount;
}
}
}
This isn't associative though.
So currently, say I have one category with two products then they all print out as a single array
array({
1:category_name
2:category_desc
3:category_code
4:item_code
5:description
6:color
7:sector
8:code
9:description
10:quantity
11:amount
12:item_code
13:description
14:color
15:sector
16:code
17:description
18:quantity
19:amount
})
I'd like to get a structure where the parent level is the category_code with it's name and description, then each item_code and their own info like so:
array({
category_name
category_desc
category_code
Array(
1: item_code array(
details array(
description
color
sector
)
code
description
quantity
amount)
2: item_code array(
details array(
description
color
sector
)
code
description
quantity
amount)
)
})
How can I modify this to create the levels like I need so that it formats properly when I export to a spreadsheet
You need to split you code and init new object in the loop.
Consider the following (notice the comment in the code)
$allCategoryResult= array(); // init at first - notice naming as category and not prices
foreach($prices->categories as $category){
$categoryItem = array(); // as current category to populate
// give name to the keys and not just numbers
$categoryItem["name"] = $category->category_name;
$categoryItem["desc"] = $category->category_desc;
$categoryItem["code"] = $category->category_code;
foreach($category->products as $product){
$productItem = array(); // new product, so init new array for him
// fill all the item data with name - maybe you will need to fix the paths here
$productItem["details"] = array(); // init empty array for all the details elements
foreach ($product->product_info->details as $details) {
$detailsItem = array(); // init details array for each detail element
$detailsItem["description"] = $details->description;
$detailsItem["color"] = $details->color;
$detailsItem["sector"] = $details->sector;
$productItem["details"][] = $detailsItem; // add the detail element to the product array
}
$productItem["code"] = $product->product_info->code;
$productItem["itemDescription"] = $product->product_info->item->description;
$productItem["quantity"] = $product->product_info->item->item_type->quantity;
$productItem["amount"] = get_object_vars($product->prices);
$itemCode = $product->product_info->item->item_code;
categoryItem[$itemCode] = $productItem; // add the product to category array by his code
}
$allCategoryResult[] = $categoryItem; //add the category to all category array
}
Writing this without see you actual data is pretty hard - so I guess you will have to modify it to fit your data.
But I hop you get the idea. Good luck!
I was messing around with the steam API and I found out that I was not able to get the quantity of my items. Lets say I have item A 2 times, it does not show the picture just 1 time with the quantity set to "2", but instead it shows the item twice with the quantity set to 1.
This is the part I use to get the inventory.
$backpackURL = "http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=" . $APIkey . "&SteamID=" . $profile . "&format=json";
$schemaURL = "http://api.steampowered.com/IEconItems_440/GetSchema/v0001/?key=" . $APIkey . "&language=en";
$userBackpack = json_decode(file_get_contents($backpackURL), true);
$itemSchema = json_decode(file_get_contents($schemaURL), true);
$backpack_items = $userBackpack['result'];
$schema_items = $itemSchema['result'];
And here I list all the items:
foreach($backpack_items['items'] as $ind=>$backpack_items){
$id = $backpack_items['id'];
$defindex = $backpack_items['defindex'];
$name = getItemName($schema_items, $defindex, $image_url);
$quantity = $backpack_items['quantity'];
$inventory = $backpack_items['inventory'];
echo '
$tmp[] = $backpack_items; print_r($tmp)
';
}
Since there is no ID to see if there are any duplicates, you can try to merge them by name.
By reading this code, it first creates a copy of the main array.
I loop over the main array, then again over the copy. So for each value of the main array, a complete cycle of the array is done again for values to compare against.
Since it is expected that there is atleast 1 name, I don't unset immidiatly, but only after another result is found, hence the $b.
It's quantity is increased if a dupe is found, on the key of the main loop.
$copy = $backpack_items['items'];
foreach($backpack_items['items'] as $k => $v){
$b = false;
$s = '';
$n = getItemName($schema_items, $v['defindex'], $s);
foreach($copy as $k2 => $v2){
if($n == getItemName($schema_items, $v2['defindex'], $s)){
if(!$b){
$b = $k;
} else {
unset($backpack_items['items'][$k2]);
$backpack_items['items'][$k]['quantity'] += 1;
}
}
}
}
// Now use your original loop, and the dupes should be removed.
I am facing problem to retrieve records in descending order with pagination limit from amazon dynamodb as in mysql.
Now I am using the following script, but it gives unordered list of records. I need the last inserted id is on top.
$limit = 10;
$total = 0;
$start_key = null;
$params = array('TableName' => 'event','AttributesToGet' =>array('id','interactiondate','repname','totalamount','fooding','nonfooding','pdfdocument','isMultiple','payment_mode','interaction_type','products','programTitle','venue','workstepId','foodingOther','interaction_type_other'), 'ScanFilter'=> array('manufacturername' => array("ComparisonOperator" => "EQ", "AttributeValueList" => array(array("S" => "$manufacturername")))),'Limit'=>$limit );
$itemsArray = array();
$itemsArray = array();
$finalItemsArray = array();
$finalCRMRecords = array();
do{
if(!empty($start_key)){
$params['ExclusiveStartKey'] = $start_key->getArrayCopy();
}
$response = $this->Amazon->Dynamodb->scan($params);
if ($response->status == 200) {
$counter = (string) $response->body->Count;
$total += $counter;
foreach($response->body->Items as $itemsArray){
$finalItemsArray[] = $itemsArray;
}
if($total>$limit){
$i =1;
foreach($response->body->Items as $items){
$finalItemsArray[] = $items;
if($i == $limit){
$start_key = $items->id->{AmazonDynamoDB::TYPE_NUMBER}->to_array();
$finalCRMRecords['data'] = $finalItemsArray;
$finalCRMRecords['start_key'] = $start_key;
break;
}
$i++;
}
}elseif($total<$limit){
$start_key = $response->body->LastEvaluatedKey->to_array();
}else{
$finalCRMRecords['data'] = $finalItemsArray;
if ($response->body->LastEvaluatedKey) {
$start_key =$response->body->LastEvaluatedKey->to_array();
break;
} else {
$start_key = null;
}
$finalCRMRecords['start_key'] = $start_key;
}
}
}while($start_key);
Regards
Sandeep Kumar Sinha
A Scan operation in DynamoDB can not change the sorting of the returned items. Also is Scan a pretty expensive operation as it always requires to read the whole table.
If you want to take advantage of DynamoDB, here's one advice:
Instead of looking for information, try to just find it.
In the sense of, use lookups instead of scan/query to get the information you need.
As an example, if you have a table that stores Events. Just store all events in that table, with their EventId as HashKey. Then you can have a second table EventLookups to store lookups to EventIds. In the EventLookups table you could put an Item like LookupId: LATEST-EVENT referencing some EventId: .... Every time you insert new events you can update the LATEST-EVENT entry to point to a newer Event. Or use a SET to store the latest 50 EventIds events in one Item.
-mathias
I'm currently experiencing a memory usage issue - but I cannot figure out where. I've tried replacing some of my foreach loops with for loops or by issuing another query to the DB, but I am still gettting the same error - "Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in on line 109". Can anyone provide some insight as to what may be causing the issue? Thank you!
Code after #Patrick 's answer:
$participating_swimmers = array();
$event_standings = array();
$qualifying_times = array();
$events = array();
$current_event = '';
$select_times_sql = "SELECT event, time, name, year, team, time_standard, date_swum
FROM demo_times_table
WHERE sex = 'M' AND (time_standard = 'A' OR time_standard = 'B')
ORDER BY event, time ASC";
$select_times_query = mysql_query($select_times_sql);
//Create array with the current line's swimmer's info
while ($swimmer_info = mysql_fetch_assoc($select_times_query)) {
if($current_event != $swimmer_info['event']){
$events[] = $current_event = $swimmer_info['event'];
}
//Create array with the current line's swimmer's info
$swimmer_info["time"] = $select_times_row['time'];
$swimmer_info["name"] = $select_times_row['name'];
$swimmer_info["year"] = $select_times_row['year'];
$swimmer_info["team"] = $select_times_row['team'];
$swimmer_info["time_standard"] = $select_times_row['time_standard'];
$swimmer_info["date_swum"] = $select_times_row['date_swum'];
//Create "Top 8" list - if more than 8 A cuts, take them all
if (($swimmer_info["time_standard"] == "A") || ($swimmer_info["time_standard"] == "B")) {
//Check if there are 8 or less entries in the current event, or if the swim is an A cut
if ((count($event_standings[$current_event]) < 8) || ($swimmer_info["time_standard"] == "A")) {
//Add swimmer to the list of invites
$event_standings[$current_event][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
} else {
//Add the qualifying time that did not fit into the list to a list of qualifying times
$qualifying_times[$current_event][] = $swimmer_info;
}
}
}
//Sort each array of times in descending order
arsort($event_standings);
arsort($qualifying_times);
$num_of_swimmers = count($participating_swimmers);
while ($num_of_swimmers < 80) {
foreach ($events as $loe) {
$num_of_qualifying_times = count($qualifying_times[$loe]);
$swimmer_info = $qualifying_times[$loe][$num_of_qualifying_times-1];
$event_standings[$loe][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
//Remove time from array of qualifying times
unset($qualifying_times[$loe][$num_of_qualifying_times-1]);
}
$new_num_of_swimmers = count($participating_swimmers);
if($num_of_swimmers == $new_num_of_swimmers) break;
else $num_of_swimmers = $new_num_of_swimmers;
}
arsort($event_standings);
arsort($qualifying_times);
foreach($event_standings as $loe => $event_swimmer) {
echo "<h1>",$loe,"</h1><br />";
foreach ($event_swimmer as $es) {
echo $es["time"]," ",$es["name"]," ",$es["team"],"<br />";
}
}
Large data in database is the problem 95% !
- try using limit x,y in your queries , and put those queries in some loop .
- see http://php.net/manual/en/function.mysql-free-result.php it might help
<?php
$participating_swimmers = array();
$event_standings = array();
$qualifying_times = array();
$select_times_sql = "SELECT *
FROM demo_times_table
WHERE sex = 'M'
ORDER BY time ASC";
$select_times_query = mysql_query($select_times_sql);
while ($select_times_row = mysql_fetch_assoc($select_times_query)) {
//Create array with the current line's swimmer's info
$swimmer_info["time"] = $select_times_row['time'];
$swimmer_info["name"] = $select_times_row['name'];
$swimmer_info["year"] = $select_times_row['year'];
$swimmer_info["team"] = $select_times_row['team'];
$swimmer_info["time_standard"] = $select_times_row['time_standard'];
$swimmer_info["date_swum"] = $select_times_row['date_swum'];
//Create "Top 8" list - if more than 8 A cuts, take them all
if (($swimmer_info["time_standard"] == "A") || ($swimmer_info["time_standard"] == "B")) {
//Check if there are 8 or less entries in the current event, or if the swim is an A cut
if ((count($event_standings[$current_event]) < 8) || ($swimmer_info["time_standard"] == "A")) {
//Add swimmer to the list of invites
$event_standings[$current_event][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
} else {
//Add the qualifying time that did not fit into the list to a list of qualifying times
$qualifying_times[$current_event][] = $swimmer_info;
}
}
}
mysql_free_result($select_times_query);
//Sort each array of times in descending order
arsort($event_standings);
arsort($qualifying_times);
$num_of_swimmers = count($participating_swimmers);
$sql = "SELECT DISTINCT(event)
FROM demo_times_table
WHERE sex = 'M' limit 80";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
$loe = $row['event'];
$num_of_qualifying_times = count($qualifying_times[$loe]);
$event_standings[$loe][] = $qualifying_times[$loe][$num_of_qualifying_times-1];
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $qualifying_times[$loe][$num_of_qualifying_times]["name"];
$condensed_swimmer_info["year"] = $qualifying_times[$loe][$num_of_qualifying_times]["year"];
$condensed_swimmer_info["team"] = $qualifying_times[$loe][$num_of_qualifying_times]["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
//Remove time from array of qualifying times
unset($qualifying_times[$loe][$num_of_qualifying_times-1]);
}
$num_of_swimmers = count($participating_swimmers);
mysql_free_result($query);
arsort($event_standings);
arsort($qualifying_times);
$sql = "SELECT DISTINCT(event)
FROM demo_times_table
WHERE sex = 'M'";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
$loe = $row['event'];
echo "<h1>".$loe."</h1><br />";
foreach ($event_standings[$loe] as $es) {
echo $es["time"]." ".$es["name"]." ".$es["team"]."<br />";
}
}
/*
foreach ($participating_swimmers as $ps) {
echo $ps["name"]."<br /><br />";
}
echo "<br /><br />";
*/
?>
Instead of doing a query within a query, with the potential for logic holes that create a never-ending loop, you can condense it into a single query. For your first block, both loops are just checking for the current event and the sex of the participant, right? So:
$result = SELECT * FROM <my database> WHERE sex = 'M' ORDER BY time ASC
Then you can pull whichever rows you want during the while ($row = mysql_fetch_assoc($result)) loop and compensate for non-distinct values in another way.
One other source of the never-ending loop could be in the block where you sort the qualifying times. You're using "unset" after each, which could be getting the pointer stuck. You could try adding array_values($qualifying_times) after the unset to reindex the array.
Frist off, lose the SELECT DISTINCT like so:
$events = array()
$current_event = '';
$select_times_sql = "SELECT event, time, name, year, team, time_standard, date_swum
FROM demo_times_table
WHERE sex = 'M' AND (time_standard = 'A' OR time_standard = 'B')
ORDER BY event, time ASC";
$select_times_query = mysql_query($select_times_sql);
//Create array with the current line's swimmer's info
while ($swimmer_info = mysql_fetch_assoc($select_times_query)) {
if($current_event != swimmer_info['event']){
$events[] = $current_event = $swimmer_info['event'];
}
//Create "Top 8" list - if more than 8 A cuts, take them all
//Check if there are 8 or less entries in the current event, or if the swim is an A cut
This also loses a bit of redundant code, and can speed up the final output (note the commas in the echo statements - the string doesn't need to be concatenated before it is spat out)
foreach($event_standings as $loe => $event_swimmer) {
echo "<h1>",$loe,"</h1><br />";
foreach ($event_swimmer as $es) {
echo $es["time"]," ",$es["name"]," ",$es["team"],"<br />";
}
}
The final problem lies in the second while loop, where the info being put into $condensed_swimmer_info doesn't have the -1 in place, thus is always blank, and $num_of_swimmers never rises to more than 1 over its original value:
while ($num_of_swimmers < 80) {
foreach ($events as $loe) {
$loe = $row['event'];
$num_of_qualifying_times = count($qualifying_times[$loe]);
$swimmer_info = $qualifying_times[$loe][$num_of_qualifying_times-1];
$event_standings[$loe][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
//Remove time from array of qualifying times
unset($qualifying_times[$loe][$num_of_qualifying_times-1]);
}
$new_num_of_swimmers = count($participating_swimmers);
if($num_of_swimmers == $new_num_of_swimmers) break;
else $num_of_swimmers = $new_num_of_swimmers;
}