php根据json其中的一个键值大小重新排序 15
{"data":[{"num":"20","sex":"0"},{"num":"35","sex":"1"},{"num":"16","sex":"0"}]}想通过php...
{
"data":[
{"num":"20","sex":"0"},
{"num":"35","sex":"1"},
{"num":"16","sex":"0"}
]
}
想通过php按num从小到大重新排序,生成
{
"data":[
{"num":"16","sex":"0"},
{"num":"20","sex":"0"},
{"num":"35","sex":"1"}
]
} 展开
"data":[
{"num":"20","sex":"0"},
{"num":"35","sex":"1"},
{"num":"16","sex":"0"}
]
}
想通过php按num从小到大重新排序,生成
{
"data":[
{"num":"16","sex":"0"},
{"num":"20","sex":"0"},
{"num":"35","sex":"1"}
]
} 展开
展开全部
在php对json直接操作成本太高,所以应该将json先转化为数组,对数组排序就很好弄了,具体操作如下:
//先将json转化为数组:
$people =json_decode($people,true);
//排序方法
function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
if(is_array($arrays)){
foreach ($arrays as $array){
if(is_array($array)){
$key_arrays[] = $array[$sort_key];
}else{
return false;
}
}
}else{
return false;
}
array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
return $arrays;
}
//测试效果
$person = array(
array('num'=>1,'sex'=>'1'),
array('num'=>2,'sex'=>'0'),
array('num'=>3,'sex'=>'1'),
array('num'=>4,'sex'=>'1'),
array('num'=>5,'sex'=>'0'),
array('num'=>6,'sex'=>'0'),
array('num'=>7,'sex'=>'0')
);
var_dump($person);
$person = my_sort($person,'num',SORT_ASC,SORT_STRING);
var_dump($person);
$person = my_sort($person,'sex');
var_dump($person);
//先将json转化为数组:
$people =json_decode($people,true);
//排序方法
function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
if(is_array($arrays)){
foreach ($arrays as $array){
if(is_array($array)){
$key_arrays[] = $array[$sort_key];
}else{
return false;
}
}
}else{
return false;
}
array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
return $arrays;
}
//测试效果
$person = array(
array('num'=>1,'sex'=>'1'),
array('num'=>2,'sex'=>'0'),
array('num'=>3,'sex'=>'1'),
array('num'=>4,'sex'=>'1'),
array('num'=>5,'sex'=>'0'),
array('num'=>6,'sex'=>'0'),
array('num'=>7,'sex'=>'0')
);
var_dump($person);
$person = my_sort($person,'num',SORT_ASC,SORT_STRING);
var_dump($person);
$person = my_sort($person,'sex');
var_dump($person);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |