【问题标题】:Sorting a PHP array according to a certain column [duplicate]根据某一列对PHP数组进行排序[重复]
【发布时间】:2016-06-18 10:01:35
【问题描述】:

我有以下 JSON:

    [{
      "id":"1",
      "testimony":"I recently went to Perceptive Mind on behalf of a client to get assistance in the web-development of an online invoicing system.\n\t\t\t\t\t\t\t\t\t\t\t\t\tThe work they did for me was done quickly and with great care. What I found most notable about Perceptive Mind was that it worked with my budget, I didn't feel overcharged and had plenty of tech support and communication throughout the project.\n\t\t\t\t\t\t\t\t\t\t\t\t\tI will definitely be using Perceptive Mind in the future!",
      "author":"Miles Hellyer",
      "title":"Founder",
      "company":"Chalk Marketing",
      "sort_order":"200"
   },
   {
      "id":"2",
      "testimony":"Just like to thank Nick for\r\n\t\t\t\t\t\t\t\t\t\t\t\t\this outstanding and professional work, he has created a great website\r\n\t\t\t\t\t\t\t\t\t\t\t\t\twhich suits our needs. He was efficient, helpful and very\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tfriendly! Definitely would recommend using his services",
      "author":"Jennifer Mouhaweg",
      "title":"Manager",
      "company":"The Lockout Guys",
      "sort_order":"400"
   }]

这是我解码 JSON 并将其放入 PHP 数组的代码:

$testimonials_array;
        $testimonials_table_json = json_decode(file_get_contents('../app/database/testimonials.JSON'),true);
        foreach($testimonials_table_json as $row) {
            $testimonial = $this->model('TestimonialModel');
            $testimonial->testimony = $row['testimony'];
            $testimonial->author = $row['author'];
            $testimonial->title = $row['title'];
            $testimonial->company = $row['company'];

            $testimonials_array[] = $testimonial;
        }

        return $testimonials_array;

我的问题是,如果我添加一个$testimonial->sort_order= $row['sort_order'];,我可以使用它对$testimonial 数组进行排序吗?有没有办法在foreach 循环之前对其进行排序?

【问题讨论】:

  • 你试过this吗?

标签: php arrays json sorting


【解决方案1】:

使用usort:

usort($testimonials_table_json, function ($a, $b) {
  return $b['sort_order'] - $a['sort_order'];
});

【讨论】:

  • 成功了,谢谢。
猜你喜欢
  • 2011-10-28
  • 2013-12-24
  • 2018-12-08
  • 2016-11-18
  • 1970-01-01
  • 2015-08-21
  • 2020-09-08
  • 2011-02-11
  • 2011-12-15
相关资源
最近更新 更多