i need to sort an array like this in function of the price:
Array
(
[SJ] => Array
(
[desc] => Junior Suite
[solutions] => Array
(
[0] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 607.08
[status] => OK
[policy] => 1
[currency] => EU
)
[1] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 700.80
[status] => OK
[policy] => 1
[currency] => EU
)
)
)
[MZ] => Array
(
[desc] => Doble Deluxe con hidromasaje
[solutions] => Array
(
[0] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 518.40
[status] => OK
[policy] => 1
[currency] => EU
)
)
)
)
Can someone give me the right way to do that? :)
EXPECTED RESULT
Array
(
[MZ] => Array
(
[desc] => Doble Deluxe con hidromasaje
[solutions] => Array
(
[0] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 518.40
[status] => OK
[policy] => 1
[currency] => EU
)
)
)
[SJ] => Array
(
[desc] => Junior Suite
[solutions] => Array
(
[0] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 607.08
[status] => OK
[policy] => 1
[currency] => EU
)
[1] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 700.80
[status] => OK
[policy] => 1
[currency] => EU
)
)
)
)
What i need is to order that array in function of price.
So if i have many solutions, i need to take the one that have minor price
You can use the PHP function usort like this:
function sortInnerPrice($a, $b) {
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? -1 : 1;
}
// First sort the inner prices
foreach ($test as $key => $val) {
usort($test[$key]['solutions'], 'sortInnerPrice');
}
function cmp($a, $b)
{
$aPrice = $a['solutions'][0]['price'];
$bPrice = $b['solutions'][0]['price'];
if ($aPrice == $bPrice) {
return 0;
}
return ($aPrice < $bPrice) ? -1 : 1;
}
// Then sort by lowest solution price
usort($yourArray, "cmp");
usort is a PHP function that allows you to sort an array based on whatever you want. You create a function that will return 0 if they are the same, -1 if you want $a before $b, and 1 if you want $a after $b.
Try to make another array containing all the prices and then use array_multisort for it
Related
This question already has answers here:
Sort an array of associative arrays by column value
(23 answers)
Closed 2 years ago.
I want to sort a nested array by number. So that in each category the products with the biggest number comes first.
I tried something i found here.
How to Sort Multi-dimensional Array by Value?
usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
but found no solution to make it work. Especially because i don't know each productnumber (e.g.sdk38z3) inside one category (e.g. chocholate - sugar - candy).
In my case i used uasort instead of usort.
Array
(
[apple - oranges - bananas] => Array
(
[fn7z3] => Array
(
[slider_details] =>
[productnumber] => fn7z3
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 30
[oneString] =>
)
)
[chocholate - sugar - candy] => Array
(
[sdk38z3] => Array
(
[slider_details] =>
[productnumber] => sdk38z3
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 45
[oneString] =>
)
[g433] => Array
(
[slider_details] =>
[productnumber] => g433
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 2
[oneString] =>
)
[j8z28] => Array
(
[slider_details] =>
[productnumber] => j8z28
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 250
[oneString] =>
)
[73hf873] => Array
(
[slider_details] =>
[productnumber] => 73hf873
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 30
[oneString] =>
)
)
Result i want:
Array
(
[apple - oranges - bananas] => Array
(
[fn7z3] => Array
(
[slider_details] =>
[productnumber] => fn7z3
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 30
[oneString] =>
)
)
[chocholate - sugar - candy] => Array
(
[j8z28] => Array
(
[slider_details] =>
[productnumber] => j8z28
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 250
[oneString] =>
)
[sdk38z3] => Array
(
[slider_details] =>
[productnumber] => sdk38z3
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 45
[oneString] =>
)
[73hf873] => Array
(
[slider_details] =>
[productnumber] => 73hf873
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 30
[oneString] =>
)
[g433] => Array
(
[slider_details] =>
[productnumber] => g433
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 2
[oneString] =>
)
)
I finally found a solution for my problem, by using a function given in this answer:
How to sort an array of associative arrays by value of a given key in PHP?
Because i don't really know the key i need i used a foreach loop with the $key functionality.
I needed to override my actual array with the sorted array too, to make changes permanent.
In my case, as i said, im using uasort instead of usort, because im using names as Key.
Explanation of variables:
$similarProducts = my whole array.
$attributeCombination = for Example [apple - oranges - bananas]
function invenDescSort($item1, $item2)
{
if ($item1['number'] == $item2['number']) return 0;
return ($item1['number'] < $item2['number']) ? 1 : -1;
}
foreach ($similarProducts AS $key => $attributeCombination) {
uasort($attributeCombination, 'invenDescSort');
$this->similarProducts[$key] = $attributeCombination;
//print_r($attributeCombination);
}
My array look like this :
[cart_seller] => Array
(
[3] => Array
(
[หมวด1เลือก1 หมวด2เลือก1 1705] => Array
(
)
)
[4] => Array
(
[# 801] => Array
(
)
)
)
[cart_product] => Array
(
[หมวด1เลือก1 หมวด2เลือก1 1705] => Array
(
[id] => 1705
[name] => ทดสอบสินค้า
[image] => p1534937865-VASAVAT LAB N MEDIA LOGO W.png
[price] => 1111
[option] => หมวด1เลือก1 หมวด2เลือก1
[amount] => 1
)
[# 801] => Array
(
[id] => 801
[name] => โบว์แพรแถบ ร.9 ชนมพรรษา 84 พรรษา ปีพุทธศักราช 2554
[image] => p1498062217-ส.jpg
[price] => 90
[option] =>
[amount] => 1
)
)
I want unset '# 801' in cart_seller and cart_product
in cart_product use unset($cart['cart_product'][# 801]);
but in cart_seller it in array [4] what can i do without reference value (4) ?
exapmle unset($cart['cart_seller'][xxxx][# 801]);
Just loop cart seller array til you find #801.
foreach($cart['cart_seller'] as $key => $c){
if(array_key_exists("#801",$c)){
unset($cart['cart_seller'][$key]['#801']);
}
}
I have an array with a structure like this
$product_array sample=
[0] => Array
(
[title] => M-SPA Super Camaro B-150 6-Person Inflatable Bubble Spa
[image] => http://ecx.images-amazon.com/images/I/41F6FuitoYL._SL160_.jpg
[link] => http://www.amazon.com/stuff
[price] => 960.01
[merchant] => amazon
[discount] => 16
[brand] => M-SPA
)
[1] => Array
(
[title] => M Spa Model B-130 Camaro Hot Tub, 71 by 71 by 28-Inch, Gray
[image] => http://ecx.images-amazon.com/images/I/41zQwjaPqOL._SL160_.jpg
[link] => http://www.amazon.com/stuff
[price] => 695.01
[merchant] => amazon
[discount] =>
[brand] => M-SPA
)
[2] => Array
(
[title] => M-SPA B-121 4-Person Inflatable Bubble Spa, Castello
[image] => http://ecx.images-amazon.com/images/I/41gnYSSVD5L._SL160_.jpg
[link] => http://www.amazon.com/stuff
[price] => 1,016.25
[merchant] => amazon
[discount] =>
[brand] => M-SPA
)
I cannot order this array with the price lowest to highest..
This code is not working
function order_by_price($a, $b) {
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? -1 : 1;
}
usort($product_array,order_by_price);
What am I missing
Thanks
You have a non-well formed numeric value in the last array element ... [price] => 1,016.25 .... It's a "money format" and should be presented as a string: [price] => "1,016.25".
Also, there's a certain caution with usort parameters:
Caution: Returning non-integer values from the comparison function,
such as float, will result in an internal cast to integer of the
callback's return value. So values such as 0.99 and 0.1 will both be
cast to an integer value of 0, which will compare such values as
equal.
After proper replacing(formatting) change your code as shown below:
function order_by_price($a, $b) {
$floats = str_replace(",", "", [$a['price'], $b['price']]);
return ($floats[0] == $floats[1])? 0 : (($floats[0] < $floats[1]) ? -1 : 1);
}
usort($product_array,"order_by_price");
The above will work as expected ...
The result of print_r($data['SearchAvailResponse']['Hotel']) :
Array
(
[0] => Array
(
[HotelNo] => 1
[HCode] => IDJKT_00085
[Name] => Cebu Grand Hotel
[Currency] => USD
[TotalRate] => 56
)
[1] => Array
(
[HotelNo] => 2
[HCode] => IDJKT_00094
[Name] => Best Western Plus Lex Cebu
[Currency] => USD
[TotalRate] => 65
)
[2] => Array
(
[HotelNo] => 3
[HCode] => IDJKT_00102
[Name] => Best Western Sand Bar
[Currency] => USD
[TotalRate] => 93
)
[3] => Array
(
[HotelNo] => 4
[HCode] => IDJKT_00106
[Name] => Goldberry Suites & Hotel
[Currency] => USD
[TotalRate] => 51
)
)
TotalRate tag is hotel price
I want to find the lowest price of all hotels
How do I find the lowest price of all hotels?
Any help much appreciated
Cheers
$cheapesthotel = array();
foreach($data['SearchAvailResponse']['Hotel'] as $hotel){
if($cheapesthotel == array()){
$cheapesthotel = $hotel;
} elseif ($hotel['TotalRate'] < $cheapesthotel['TotalRate']){
$cheapesthotel = $hotel;
}
}
function getMin($array)
{
$currentMin = 10000;
$minObject = Array();
foreach($array as $val)
{
if($val[totalRate] < $currentMin)
{
$minObject = $val;
}
}
return minObject;
}
How would i get the value of a key in an array?
The array is done by google shopping api which is:
// Valid source values are "public", "cx:cse", and "gan:pid"
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#products-feed
$source = "public";
// For more information about full text search with the shopping API, please
// see http://code.google.com/apis/shopping/search/v1/getting_started.html#text-search
$query = "\"mp3 player\" | ipod";
//The order in which the API returns products is defined by a ranking criterion.
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#ranking
$ranking = "relevancy";
$results = $service->products->listProducts($source, array(
"country" => "UK",
"q" => $query,
"rankBy" => $ranking,
));
print "<h1>Shopping Results</h1><pre>" . print_r($results, true) . "</pre>";
I have the following array which outputs:
Shopping Results
Array
(
[kind] => shopping#products
[etag] => "*********"
[id] => tag:google.com,2010:shopping/products
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy
[nextLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy&startIndex=26
[totalItems] => 771622
[startIndex] => 1
[itemsPerPage] => 25
[currentItemCount] => 25
[requestId] => 0CMjH976CqbECFYNWtAodLRwAAA
[items] => Array
(
[0] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/11254757413841304510
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/11254757413841304510
[product] => Array
(
[googleId] => 11254757413841304510
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[description] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[link] => http://www.amazon.co.uk/dp/B0040GIZTI/ref=asc_df_B0040GIZTI8843997?smid=A1YZ4RXO7GUOYN&tag=googlecouk06-21&linkCode=asn&creative=22218&creativeASIN=B0040GIZTI
[brand] => Apple
[condition] => new
[gtin] => 00885909394739
[gtins] => Array
(
[0] => 00885909394739
)
[mpns] => Array
(
[0] => MC540BT/A
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 135.95
[shipping] => 1.99
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/41p2rNmazRL.jpg
[status] => available
)
)
)
)
[1] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/4597224105326146239
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/4597224105326146239
[product] => Array
(
[googleId] => 4597224105326146239
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => SanDisk Sansa Clip+ 8GB MP3 Player with Radio and Expandable MicroSD/SDHC Slot - Black
[description] => 8 GB memory Digital FM-tuner with 40 preset radio stations Extendable microSD/microSDHC card slot
[link] => http://www.amazon.co.uk/dp/B002NX0ME6/ref=asc_df_B002NX0ME68843997?smid=A3P5ROKL5A1OLE&tag=googlecouk06-21&linkCode=asn&creative=22206&creativeASIN=B002NX0ME6
[brand] => SanDisk
[condition] => new
[gtin] => 00619659059989
[gtins] => Array
(
[0] => 00619659059989
)
[mpns] => Array
(
[0] => SDMX18-008G-E46K
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 46.95
[shipping] => 0
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/419U6bYDF1L.jpg
[status] => available
)
)
)
)
I don't need all this data i just need 3-4 of the keys but how would i access them? How would i echo the value of say [title] from each array?
This should work:
foreach( $results as $result)
foreach( $result['product'] as $product)
echo $product['title'];
You could either loop through the array like pointed out above or possibly use array_walk_recursive like this:
$title_array = array();
array_walk_recursive($input_array, 'find_titles');
function find_titles($value, $key) {
global $title_array;
if ($key == 'title') {
$title_array[] = $value;
}
}
This might be a better solution if you you are not certain what the structure of the input array will be (i.e. how many levels deep the key you are looking for is nested).
To output the title of each product in $results:
foreach ($results as $result) {
echo $result['product']['title'];
}
Consider using array_walk_recursive
Working example
<?php
$a = array("hai", array("ha"=>1, "hai"=>2, array("a"=>1, "b"=>2)));
function test($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($a, 'test');
0 holds hai
ha holds 1
hai holds 2
a holds 1
b holds 2
If you are interested only in title
Consider using foreach
foreach($results['item'] as $result) {
echo $result['product']['title'];
}