[英]How to sort and display JSON objects based on one key value in php
I receive data by JSON and I can read the data and show it by the icons in one big list how they were received. 我通过JSON接收数据,我可以读取数据并通过一个大列表中的图标显示如何接收它们。 What I want to do is sort the objects by price and display them as icons in two columns on a page.
我要做的是按价格对对象进行排序,并在页面上的两列中将它们显示为图标。
In one column the free items (price = 0) and in the other column the paid items (price > 0) 一栏中是免费商品(价格= 0),另一栏中是付费商品(价格> 0)
I assume I have to use usort (which I don't really understand), but I have no idea, how it would be placed into my existing code and how I could create the divs to show the icons in two columns left and right. 我假设我必须使用usort(我不太了解),但是我不知道如何将其放置到现有代码中以及如何创建div以在左右两栏中显示图标。
This is my simplified code right now: 这是我现在的简化代码:
$arr = json_decode($jsondata,true);
if ($arr['resultCount'] > '0') {
foreach($arr['results'] as $item) {
$icon = $item['artwork'];
$title = $item['trackName'];
$price = $item['price'];
if ($price == 0 ) {
echo '<div class="iconsearch" style="background-image: url('.$icon.');"><a href="'.$title.'">'.$title.'<img src="images/iconmask.png"/></a></div>';
} else {
echo '<div class="iconsearch" style="background-image: url('.$icon.');"><a href="'.$title.'">'.$title.'<img src="images/iconmask.png"/></a></div>';
}
}
}
you need to sort the results coming in. For this you should use usort
and provide your own functionality: 您需要对输入的结果进行排序。为此,您应该使用
usort
并提供您自己的功能:
usort — Sort an array by values using a user-defined comparison function
usort — 使用用户定义的比较函数按值对数组进行排序
try the following: 尝试以下方法:
if ($arr['resultCount'] > 0) {
usort($arr['results'], function ($a, $b) {
return $a["price"] > $b["price"];
});
var_dump($arr['results']);
//.. now that its sorted, you can iterate and do as you wish
}
source: http://php.net/manual/en/function.usort.php 来源: http : //php.net/manual/en/function.usort.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.