当前位置: 首页> 问答> 正文

uasort排序无效,请教大家,我的代码有什么问题吗?

  • gitaspgitasp
  • 问答
  • 2024-12-29 18:29:01
  • 41

  uasort排序无效,请教大家,我的代码有什么问题吗?代码如下请帮忙看看

  public function getIndustry() {

    $res = Db::name('XXXX')

        ->where(['status'=>'normal'])

        ->select();

    if (!$res) {

        return $this->ok('请求成功', []);

    }

    $industryCat1 = [];

    $industryCat2 = [];

    $industryCat3 = [];

    foreach ($res as $key => $item) {  // 记录键值

        if ($item['level'] === 1) {

            $industryCat1[$item['id']] = ['name' => $item['name'], 'weigh' => $item['weigh']];

            $industryCat2[$item['id']] = [];

        } else if ($item['level'] === 2) {

            $industryCat2[$item['pid']][$item['id']] = ['name' => $item['name'], 'weigh' => $item['weigh']];

            $industryCat3[$item['id']] = [];

        } else if ($item['level'] === 3) {

            $industryCat3[$item['pid']][$item['id']] = ['name' => $item['name'], 'weigh' => $item['weigh']];

        }

    }

// 对 industryCat1 按 weigh 降序排序

uasort($industryCat1, function ($a, $b) {

    if ($a['weigh'] == $b['weigh']) {

        return 0;

    }

    return ($a['weigh'] < $b['weigh'])? -1 : 1;

});

    $res = [

        'industryCat1' => $industryCat1,

        'industryCat2' => $industryCat2,

        'industryCat3' => $industryCat3,

    ];

    return $this->ok('请求成功', $res);

}

image.png

对 industryCat1 按 weigh 降序排序,保留键名,但是始终无法按 weigh 降序排序,仍然按键名升序排序,请教大家,这里是不是我写的有问题?万分感谢!

uasort 这里可能有些问题,修改下面的试下 uasort ($industryCat1. function ($a, $b) { if ($a ['weigh'] == $b ['weigh']) { return 0; } return ($a ['weigh'] < $b ['weigh'])? 1 : -1; });

感谢回复,下面的应该怎么修改?您给的代码好像和我的一样。

看1 和-1 那里

最新文章