You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何对多个JSON文件的查询结果按id键值进行排序

实现方案

你需要先把所有读取到的符合条件的JSON数据存入临时数组,排序完成后再遍历输出,修改后的代码如下:

<div class="container grid grid-cols-2 gap-6 tablet:grid-cols-3 desktop:grid-cols-6">
    <?php
    // 初始化存储产品数据的数组
    $productList = [];
    $dir = (new DirectoryIterator(__DATA_PAGES_PATH__ . 'products/content/' . $lang));
    foreach ($dir as $productsdata) {
        if ($productsdata->isDot()) continue;
        $productdata = json_decode(file_get_contents(__DATA_PAGES_PATH__ . 'products/content/' . $lang . "/" . $productsdata));
        // 筛选popular>0的产品存入数组
        if ($productdata->popular > 0) {
            $productList[] = $productdata;
        }
    }

    // 按id字段升序排序
    usort($productList, function($a, $b) {
        return $a->id - $b->id;
        // 如果要实现id降序排序,修改为 return $b->id - $a->id;
    });

    // 遍历排序后的数组,最多输出6条
    $i = 0;
    foreach ($productList as $item) {
        if (++$i > 6) break;
        echo $item->id;
        // 可在此处补充其他需要输出的产品字段内容
    }
    ?>
</div>

逻辑说明

  • 先遍历目录读取所有JSON文件,将符合popular>0条件的产品对象全部存入$productList数组,暂时不输出内容
  • 调用PHP内置的usort方法,自定义排序规则实现按id字段的值排序
  • 最后遍历排序后的数组输出内容,通过计数控制最多输出6条结果

内容的提问来源于stack exchange,提问作者Kene

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:36:01