源数据:
var data = '{ "1417":{"name":"张军玲","score":"90","second":"437"}, "1431":{"name":"苏海林","score":"70","second":"288"}, "6869":{"name":"尚迎涛","score":"50","second":"66"}, "6849":{"name":"刘巧锋","score":"70","second":"150"}, "1120":{"name":"赵娜娜","score":"80","second":"330"} }';
源数据预览:
转换:
$data = json_decode($data,true); $data = scoresort($data,'score desc,second asc,name desc'); $data = json_encode($data,JSON_UNESCAPED_UNICODE); // 不encode中文
转换后预览:
转换后:
data = [ {"name":"张军玲","score":"90","second":"437"}, {"name":"赵娜娜","score":"80","second":"330"}, {"name":"刘巧锋","score":"70","second":"150"}, {"name":"苏海林","score":"70","second":"288"}, {"name":"尚迎涛","score":"50","second":"66"} ];
转换函数:
/** 积分排序 注意:二维数组、使用了eval、关联(string)键名保持不变,但数字键名会被重新索引 */ function scoresort($array, $orderStr='score desc,second asc'){ $temp = explode(',', $orderStr); $order = array(); foreach ($temp as $o) { $o = preg_split('/\s+/', trim($o)); $o[1] = isset($o[1]) ? $o[1] : 'asc'; $order[$o[0]] = $o[1]; } $parm = array(); foreach ($order as $k => $v) { ${$k} = array(); foreach ($array as $key => $value) { ${$k}[$key] = $value[$k]; // echo $value[$k]."\n"; } $v = strtoupper($v); $parm[] = '$'."$k, SORT_$v"; } $parm = implode(', ',$parm); eval('array_multisort('.$parm.', $array);'); return $array; }
官方示例:
<完>