简体   繁体   中英

Finding the lowest JSON value, from a JSON response with multiple values

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:

  • 294.00
  • 295.00
  • 296.00

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.

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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM