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);
}

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

最佳答案

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

6个月前 评论
xlv_520 (楼主) 6个月前
Chambine (作者) 6个月前
讨论数量: 11

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

6个月前 评论
xlv_520 (楼主) 6个月前
Chambine (作者) 6个月前

二维数组排序用 array_multisort

array_multisort(array_column($industryCat1, 'weigh'), SORT_DESC, $industryCat1);
6个月前 评论
xlv_520 (楼主) 6个月前
乘马班如 (作者) 6个月前

file 用的是数字键名,用uasort,一直默认键名升序,怎么排序都无效。

6个月前 评论

如果是在浏览器的控制台查看请求,点 Preview 那一栏的话,浏览器为了美观会把键升序再展示。点 Response 那一栏看到的才是原样输出,看看是不是这个原因

file

file

6个月前 评论

这里返回值弄反了,你就把它当成左右相减,返回正值,左边大(也就是第一个比第二个大,就是降序),返回负值,右边大(第一个比第二个小,升序)

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

你想要降序,就应该如下

return ($a['weigh'] < $b['weigh'])? 1 : -1;
5个月前 评论
xlv_520 (楼主) 5个月前

非常感谢版主和AaronKun,的确是搞反了。
现在又碰到一个问题了。
在wxapi中把数据都处理好了,现在微信小程序前端获取数据后,发现前端获取的数据又变成了按键名id升序排序了

 getIndustry() {
    var that = this;
    comm.cjRequest({ url: "/wxapi/getIndustry", data: {} })
      .then((res) => {
        const data = res.data.data;
        that.setData({
          industryCat1: data.industryCat1,
          industryCat2: data.industryCat2,
          industryCat3: data.industryCat3,
        });
      })
      .catch((err) => {
        console.error(err);
      });
  },
5个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!