如何在循环之前按键值对json字符串进行排序?

时间:2015-11-19 23:44:45

标签: php arrays json sorting

我想在循环之前按itemCategory_title或itemCategory_id对这种json字符串进行排序?我试图使用usort但它没有排序!

任何人都可以告诉我如何做到这一点?

json字符串示例数据:

{ '5123': {
            'tmp': '1', 'name': 'mango', 'abc': 'abcd4 http://mysite/items/1234', 'number': '1123', 'itemCategory_title': 'fruits', 'logo': '2123.png', 'itemCategory_id': '90'
        }, '700': {
            'tmp': '0', 'name': 'cherry', 'abc': 'abcd4 http://mysite/items/1235', 'number': '1124', 'itemCategory_title': 'fruits', 'logo': '2124.png', 'itemCategory_id': '91'
        } }

php代码:     

$code2 = stripslashes($_POST['outputtext']);

$clean_str = str_replace("p '","'",$code2);
$clean_str = str_replace('\'', '"', $clean_str);

$data = json_decode($clean_str, true);

//here i want to sort $data by itemCategory_title or itemCategory_id

usort($data, function($a, $b) { //Sort the array using a user defined function
    return $a->itemCategory_id > $b->itemCategory_id ? -1 : 1; //Compare the scores
}); 

foreach( $data as $item ) {
  echo $item['tmp'];
  echo $item['name'];
  echo $item['abc'];
  echo $item['number'];
  echo $item['itemCategory_title'];
  echo $item['log'];
  echo $item['itemCategory_id'];    

?>
<a href="./process.php?tmp=<?php  echo $item['tmp'] ; ?>&name=<?php  echo $item['name']; ?>&abc=<?php  echo $item['abc'] ; ?>&itemCategory_title=<?php  echo $item['itemCategory_title'] ; ?>&log=<?php  echo $item['log'] ; ?>&itemCategory_id=<?php  echo $item['itemCategory_id'] ; ?>"><?php  echo $item['itemCategory_title'] ; ?> </a> <br />
<?

}

?>

1 个答案:

答案 0 :(得分:3)

usort函数中,->itemCategory_id应为['itemCategory_id']。由于您将第二个参数赋予json_decode(),因此JSON对象将成为PHP关联数组,而不是对象。

如果您打开错误报告,则会看到有关尝试获取非对象属性的注意事项。当你在foreach循环中回显它们而不是usort比较函数时,你做对了。

usort($data, function($a, $b) { //Sort the array using a user defined function
    return $a['itemCategory_id'] > $b['itemCategory_id'] ? -1 : 1; //Compare the scores
}); 

要按类别中的名称排序,应该是:

usort($data, function($a, $b) { //Sort the array using a user defined function
  if ($a['itemCategory_id'] == $b['itemCategory_id']) {
    return $a['name'] > $b['name'] ? 1 : -1;
  } else {
    return $b['itemCategory_id'] - $a['itemCategory_id'];
  }
}); 

此类别ID按降序排序,名称升序。