按键值对ArrayObject排序

时间:2018-06-26 04:34:28

标签: php arrays json object

我在JSON文件中有此数据:

{
"1011459447787610113": {
    "cot": "negative",
    "id": "1011459447787610113",
    "name": "Mustafa",
    "location": "Lyon, France",
},
"1011459423024316417": {
    "cot": "positive",
    "id": "1011459423024316417",
    "name": "\u0627\u0644\u0639\u0627\u0634\u0642",
    "location": "",

},
"1011459422265192449": {
    "cot": "negative",
    "id": "1011459422265192449",
    "name": "Alison Bing",
    "location": "California\/Italy\/Mideast",
},
}

我正在尝试通过名为cot的键对其进行排序,该键应该对所有数组进行排序,例如“负”。

我尝试了以下代码:

$get = json_decode(file_get_contents('d.json', true));
usort($get, function($a, $b)
{
    return strcmp($a->cot, $b->cot);
});

foreach ($get as $key => $value) {
  echo '<div class="card v1card">';
  echo "$value->cot :<a href='https://twitter.com/$value->user_screen_name' target='_blank'><div class='card-header' style='padding: 5px 5px;'><img src='$value->avatar' style='border-radius: 30px !important;-webkit-box-shadow: -1px 0px 10px -5px rgba(0,0,0,0.56);-moz-box-shadow: -1px 0px 10px -5px rgba(0,0,0,0.56);box-shadow: -1px 0px 10px -5px rgba(0,0,0,0.56);' width='30' height='30'><b> $value->name</b><small class='text-muted' style='float:right;margin: 5px 0px 0px 0px;'>$value->location</small></div></a>";
  echo "<a href='https://twitter.com/$value->user_screen_name/status/$value->id' ><div style='padding: 5px 3px 5px 6px;'> $value->post_text</div></a>";
  echo "</div>";
};

我也尝试过:

    $get = json_decode(file_get_contents('d.json', true));

    foreach ($get as $key => $value) {
      usort($get, function($a, $b)
      {
          return strcmp($a->cot, $b->cot);
      });
      echo '<div class="card v1card">';
      echo "$value->cot :<a href='https://twitter.com/$value->user_screen_name' target='_blank'><div class='card-header' style='padding: 5px 5px;'><img src='$value->avatar' style='border-radius: 30px !important;-webkit-box-shadow: -1px 0px 10px -5px rgba(0,0,0,0.56);-moz-box-shadow: -1px 0px 10px -5px rgba(0,0,0,0.56);box-shadow: -1px 0px 10px -5px rgba(0,0,0,0.56);' width='30' height='30'><b> $value->name</b><small class='text-muted' style='float:right;margin: 5px 0px 0px 0px;'>$value->location</small></div></a>";
      echo "<a href='https://twitter.com/$value->user_screen_name/status/$value->id' ><div style='padding: 5px 3px 5px 6px;'> $value->post_text</div></a>";
      echo "</div>";
    };

我不断收到

之类的错误
  

usort()期望参数1为数组,给定对象or usort()   期望参数1为数组,给定字符串

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

您的语法不正确,应该是json_decode(..., true);才能使其成为数组,但是您将true作为参数传递给file_get_contents,

$get = json_decode(file_get_contents('d.json', true));

应该是

$get = json_decode(file_get_contents('d.json'), true);