我有这段代码:
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/>";
}
}
这是JSON响应(示例): http://pastebin.com/VzAG1159
如您所见,JSON响应中有多个价格值。我如何锻炼(使用PHP),最低价格?
因此,如果值如此:
它将选择294.00。不幸的是,谷歌不会将他们的回复排序为任何逻辑格式,因此最便宜的可能是中途或最后。
我不知道我会使用什么功能,即使count()似乎不起作用。
干杯。
答案 0 :(得分:1)
也许尝试一下PHP的sorting functions?
如果您只需要对价格进行排序,您可以遍历所有价格并将它们放入临时数组中,然后使用asort()
进行排序。
答案 1 :(得分:0)
这会将$obj->items
从最低价格到最高价格排序:
$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/>";
输出:
<a href="http://www.budgetpc.com.au/computer-hardware/desktop-cpus/bx80613i7970.html"></a> $578.13<br/>
的json数据