Reputation: 763
I have this code:
foreach($specs as $spec) {
if(preg_match('/^(\w+):\s*(.*?)\s\$?(\d*\.?\d*)$/', $spec, $matches)) {
list(,$tag,$name,$price) = $matches;
$url = 'https://www.googleapis.com/shopping/search/v1/public/products?country=AU&key=KEY&q=' . urlencode($name);
$obj = json_decode(file_get_contents($url));
echo "<a href=\"{$obj->items[0]->product->link}\">{$name}</a> \${$obj->items[0]->product->inventories[0]->price}<br/>";
}
}
Here's the JSON response (example): http://pastebin.com/VzAG1159
As you can see there's multiple price values in the JSON response. How can I workout (using PHP), the lowest value price?
So if the values are like so:
It will select the 294.00 one. Unfortunately Google don't sort their response in to any logical format, so the cheapest may be half way through or at the end.
I have no idea what function I would use, even count() wouldn't seem to work.
Cheers.
Upvotes: 0
Views: 176
Reputation: 54649
This will sort $obj->items
from lowest to highest price:
$obj = json_decode(file_get_contents($url));
usort($obj->items, function ($a, $b) {
return $a->product->inventories[0]->price - $b->product->inventories[0]->price;
});
echo "<a href=\"{$obj->items[0]->product->link}\">{$name}</a> \${$obj->items[0]->product->inventories[0]->price}<br/>";
Output:
<a href="http://www.budgetpc.com.au/computer-hardware/desktop-cpus/bx80613i7970.html"></a> $578.13<br/>
With the json data from: http://pastebin.com/VzAG1159
Upvotes: 0
Reputation: 644
Maybe try one of PHP's sorting functions?.
If you just need to sort prices you could loop through all the prices and put them in a temporary array that you then sort using asort()
.
Upvotes: 1