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

PHP如何按阈值价格分组产品样本数组 生成指定嵌套结构

问题原因

现有代码直接以threshold值作为外层数组的键,将同阈值样本直接存入键对应的值中,没有封装为包含threshold字段、samples子数组的分组结构,因此输出不符合要求。

修复代码

调整遍历逻辑,首次遇到某个阈值时先初始化符合结构的分组项,再将样本追加到对应分组的samples数组下,最后用array_values重置外层数组的数字索引即可:

$sortedProducts = [];

foreach ($fetchSamples as $sample) {
    $thresholdVal = $sample['threshold'];
    // 对应阈值分组不存在时先初始化结构
    if (!isset($sortedProducts[$thresholdVal])) {
        $sortedProducts[$thresholdVal] = [
            'threshold' => (float)$thresholdVal, // 如需保留字符串类型删除(float)强转即可
            'samples' => []
        ];
    }
    // 追加样本到对应分组的samples数组
    $sortedProducts[$thresholdVal]['samples'][] = $sample;
}

// 去除外层关联键,转为顺序索引数组
$sortedProducts = array_values($sortedProducts);
输出结果

执行后得到的结构和预期完全匹配:

[
  {
    "threshold": 20.00,
    "samples": [
      {
        "sampleid": "1234",
        "productid": "11111",
        "threshold": "20.00",
        "stock": "345",
        "product": "Beauty sample 1"
      },
      {
        "sampleid": "5678",
        "productid": "22222",
        "threshold": "20.00",
        "stock": "2449",
        "product": "Beauty sample 2"
      }
    ]
  },
  {
    "threshold": 100.00,
    "samples": [
      {
        "sampleid": "999",
        "productid": "33333",
        "threshold": "100.00",
        "stock": "345",
        "product": "Beauty sample 3"
      }
    ]
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:27:47