I am sorry if my title is incorrect, was not sure what these array values are called.
I am doing an api call that returns data, i want to use that data.
Now in the data it is possible to have up to 20 'offers'.
Each has their own price.
I would like to return the lowest price
The structure of the results are
results -> 0 -> offers -> "number from 0-19" -> price
So each offer (with number 0-19) will have a price.
Is there an easy way to grab all of that data at once and just output the lowest price?
$price = $price_array['results'][0]['offers']['*can i cycle this part*']['price'];
foreach ($price_array['results'][0]['offers'] as $offer) {
echo $offer['price'];
// and do what you want
}
Or maybe:
$minPrice = min(array_column($price_array['results'][0]['offers'], 'price'));
echo $minPrice;
You can use array_column and min().
$price = min(array_column($price_array['results'][0]['offers'],'price'));
This will return the lowest price in that column of the array.
Related
I am looking to get the lowest price from some json data, I get the info from an api call, and json_decode it.
The format is:
products
productnumber -> price
$product_array['products'][..changingnumber..]['value']
I dont know the productnumber (and don't need it either). I do want find the lowestprice for all productnumbers combined
$price = min($product_array['products'][..changingnumber..]['value']);
Is there a way to do this? or is there some documentation that can help with this?
First map the 'value'-s, transform them into a simple array containing all the prices:
$all_prices = array_map(function($item) {
return $item['value'];
}, $product_array['products'])
Then just choose the minimum:
$price = min($all_prices);
Or combined into a single statement:
$price = min(array_map(function($item) {
return $item['value'];
}, $product_array['products']));
I am constructing a function that is making a call with API to db and returns me JSON data. The json contains orders and I have already decoded them in php array. Every order has properties such as "product_id" and "quantity". I want to temporarily store the "quantity" property somewhere because I need to sum all the products with the same product_id. Any suggestion how to do this?
I'm in a bit of a hurry, but wanted to see if I could help you out.
$quantities = [];
//Loop through all the orders
foreach ($orders as $order) {
//Loop through the orderrows
foreach ($order->getOrderRows() as $orderRow) {
if (array_key_exists($orderRow->getProductName(), $quantities)) {
//The product is already in the quantities array, so the quantity of this orderrow is added to the total
$quantities[$orderRow->getProductName()] =
($quantities[$orderRow->getProductName()] + (int) $orderRow->getItemQuantity());
} else {
//If this is the first time the product is encountered add the product and its quantity to the quantities array
$quantities[$orderRow->getProductName()] = (int) $orderRow->getItemQuantity();
}
}
}
This is going to have the following result, showing you the product names along with their quantities:
$quantities = [
'foo' => 12,
'bar' => 3,
];
You may use the session variable to store these values.
I have a php (5.3) file that sets a Multi-Dimensional Array
$prices = array(
array('at',$ANewPrice2,$ANewMargin,$ACode),
array('aB',$ANewPrice2,$ANewMargin,$ACode),
array('c', $NPrice2,$NPriceMargin,10),
array('d',$BW2,$BWMargin,$BWCode),
array('e', $BWU2,$BWUMargin,$BWCodeU),
array('f', $BKB2 ,$BKBMargin, $BKBCode),
array('g',$FusedPrice2,$FUsedPriceMargin,$FusedCode),
array('h',$FNew2,$FNewMargin,$FNewCode),
);
The letter is the key, the second column is the price, the third column is the margin, and the fourth column is the Qty. So what I need to do is sort them by the highest price (2nd column), and then if the value of the margin>0 then check the 4th column against a variable $qty and put the amount of the $qty into a variable so that I can insert it into a specific column of a table ( I have the table part and how to insert).
All of this is doable no problem, the kicker is that if the $qty is greater than the value of the 4th column then it needs to subtract the value of $qty from the value of the 4th column, go to the next highest price and redo the process and so on and so forth until the value of $qty is 0. I know arsort($prices); will give me the best guide, but I was wondering if there was an easy way to do this rather than a hundred nested if then statements.
You are looking for usort
Firstly define your compare callback:
function compare_price($a, $b) {
//you can do other checks here
//the function has to return an integer
return strnatcmp($a[1], $b[1]);
}
Then sort:
usort($prices, 'compare_price'); //passed by reference
Additional documentation and examples: usort Manual PHP.net
SO here is what i ended up doing
while ($qtyDistribute>0){
$prices = array(
'a' => $Price2,
'ab' => $NPrice2,
'c'=>$BW2,
'd'=>$BWU2,
'e'=>$BKB2,
'f'=>$Price2,
'g'=>$FNew2
);
if ($bestGuide=='ab'){
if($abMargin>0){
if($qtyDistribute<=10){
$abQty=$qtyDistribute;
$qtyDistribute=0;
}
else if ($qtyDistribute>10){
$abQty=10;
$qtyDistribute=($qtyDistribute-10);
$NPrice2=0;
}
}
else{
$qtyDistribute=0;
}
}
... for each price, so that once it checked the price for the highest it would simple set the price =0 and then run again until all the prices were exhausted or the qtyDistribute=0
I am writing some code to supply the Google certified shop data which I have nearly finished. I only need to supply the ship and delivery dates. I have written code to supply this information at the product level. However when there is more than one product in an order I need to select the largest ship date.
For example;
Order has two products.
Producta with $ship_date = 2 and porductb with $ship_date = 5
I need to collect all the $ship_dates (2 and 5) and return the highest one (5).
My question is simply how do I write the php to collect all the $ship_dates correctly - should I create an array and if so how?
Put all the required variables into an array, then use max.
$ship_date1 = 2;
$ship_date2 = 5;
$shipDates = [$ship_date1, $ship_date2];
// other dates as needed
// OR, a much cleaner solution, append to the array
$shipDates = [];
$shipDates[] = 2;
$shipDates[] = 5;
//No matter how you fill up the array, this is how you get its maximum value
$maxShipDate = max($shipDates);
max actually accepts individual variables instead (eg. max($ship_date1, $ship_date2);) but the array solution is easier to maintain.
OK before my foreach product loop I added this;
$deliverydatearray = array();
which creates a new (empty) array which I called $deliverydatearray
Within my foreach product loop I added this;
$deliverydatearray[] = $delivery_datep;
which adds my product specific delivery date ($delivery_datep) to my array.
After the foreach product loop has closed I can access the variables in my array. For example just printing the contents of the array is done like this;
print_r($deliverydatearray);
which looks like this;
Array
(
[0] => 2017-01-28
[1] => 2017-01-23
)
NOTE:
I'm new to php and mysql.
Background info:
I have +/- 30,000 products and they are from 7 different supplier and they have a lot of the same products
let's say i have 1 product and three of the suppliers have the it, i need to publish the product with the lowest price and the other two product stay unpublished
that is the basic idea and this must run through the 30,000 products and check and see if there are any matches and run the publishing function
SQL setup:
There are two tables xxxx_virtuemart_product and xxxx_virtuemart_product_prices
There are three rows in xxxx_virtuemart_product ▬▬▬ product_id,product_sku,published ▬▬▬
There are two rows in xxxx_virtuemart_product_prices ▬▬▬ product_id,product_price ▬▬▬
My little bit of code:
I have this little code because i'm stuck, how can i make a check to see if there are any matches and then run a query to change the published value of the product with the lowest price?
i know there is a way to use the query to check for matches, but do not understand how to do is
$query = "SELECT `product_sku` FROM `xxxx_virtuemart_product`";
$query_run = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_assoc($query_run)){
foreach ($row as $key => $ps){
}
}
The below code is to check the price (not query optimize just a rough draft)
$z = //products price;
$x = //products price;
$c = //products price;
if ($z >= $x && $c >= $x) {
//the this products published value to 1
}else if ($x >= $z && $c >= $z) {
//the this products published value to 1
}else if ($z >= $c && $x >= $c) {
//the this products published value to 1
}
Can anyone please help me with this?
Thanks for reading
any questions are welcome.
Your problem is not about to compare arrays but more algorithm.
I will try this way.
1)SQL query to retrieve all the products : sql_products
2)construct a hashmap those key is product SKU (see : PHP Array)
To construct PHP hashmap : use arrays of arrays.
Example :
product_map[] = array();
foreach sql_product of sql_products :
- product_map[sql_product[SKU]][] = array(sql_product[supplier], sql_product[price], sql_product[information])
end of loop
Then loop again over the map of products constructed and sort each product record by price : that means you have to write a function to sort array (supplier, price, information).
Now you have a map of product : SKU => array(of array (supplier, price, information))