排序JSON输出在PHP [英] Sorting JSON Output in PHP

查看:213
本文介绍了排序JSON输出在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON:

{
"row":	[
	{
	"sort":3,
	"type":"fat",
	"widgets":
		[
			{"values": [3,9] },
			{"values": [8,4] }					
		]
	},
{
	"sort":2,
	"type":"three",
	"widgets":
	[
		{"values": [3,4] },
		{"values": [12,7] },
		{"values": [12,7] }							
	]
}						
]
}

和这个PHP来输出它:

And this PHP to output it:

foreach ( $value->row as $therow )
{
	echo "<div class='row ".$therow->type."'>";

	foreach ( $therow->widgets as $thewidgets )
	{
		echo "<div class='widget'>";
		echo $thewidgets->values[0];
		echo "</div>";

	}

	echo "</div>";

}

我想这样做的排序是基于JSON,任何想法?

What I would like to do is sort the ouput based on the sort value in the JSON, any ideas?

推荐答案

使用 usort

function my_sort($a, $b)
{
    if ($a->sort < $b->sort) {
        return -1;
    } else if ($a->sort > $b->sort) {
        return 1;
    } else {
        return 0;
    }
}

usort($value->row, 'my_sort');

这篇关于排序JSON输出在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆