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

使用PHP将CSV转换为JSON并按型号分组尺寸数据

Got it, let's work through this step by step! First off, a tiny heads-up: the JSON example you shared has a syntax error—you can’t have duplicate model keys in a single JSON object. The correct structure should be an array of objects, where each object represents a grouped model. That’s easy to fix as we build the solution.

Since you already have the CSV data loaded, here’s how to group it by model and convert it to the desired JSON format:

Core Approach

  1. Group rows by model: Use a dictionary (or map) to track each model’s details, including its name and list of sizes.
  2. Populate size entries: For each CSV row, add the id and size to the corresponding model’s size list.
  3. Sort sizes: As shown in your example, sizes should be ordered numerically (9 → 10 → 11), so we’ll sort each size list by the numeric value of size.
  4. Convert to valid JSON: Turn the grouped data into an array (fixing the duplicate key issue) and serialize it to JSON.

Example Implementation (Python)

If you’re using Python, here’s a concrete code snippet using built-in csv and json modules:

import csv
import json

# Assume you already have the CSV rows loaded (this example reads from a file, adjust as needed)
model_groups = {}

# Read CSV rows (skip this part if you already have the data in memory)
with open("your_shoes.csv", "r") as csv_file:
    reader = csv.DictReader(csv_file)
    for row in reader:
        model = row["model"]
        # Initialize the group if it doesn't exist
        if model not in model_groups:
            model_groups[model] = {
                "model": model,
                "name": row["name"],
                "sizes": []
            }
        # Add the size entry to the group
        model_groups[model]["sizes"].append({
            "id": row["id"],
            "size": row["size"]
        })

# Sort each size list by numeric size value
for group in model_groups.values():
    group["sizes"].sort(key=lambda x: int(x["size"]))

# Convert to a valid JSON array and print/write to file
final_json = json.dumps(list(model_groups.values()), indent=2)
print(final_json)

Example Implementation (JavaScript)

If you’re working in JavaScript (e.g., Node.js), here’s how you’d do it:

// Assume you have the CSV data parsed into an array of objects called `shoeRows`
const modelGroups = shoeRows.reduce((acc, row) => {
    // Initialize the group if it doesn't exist
    if (!acc[row.model]) {
        acc[row.model] = {
            model: row.model,
            name: row.name,
            sizes: []
        };
    }
    // Add the size entry
    acc[row.model].sizes.push({ id: row.id, size: row.size });
    return acc;
}, {});

// Sort sizes and convert to an array
const finalShoeData = Object.values(modelGroups).map(group => {
    group.sizes.sort((a, b) => parseInt(a.size) - parseInt(b.size));
    return group;
});

// Convert to JSON
const finalJson = JSON.stringify(finalShoeData, null, 2);
console.log(finalJson);

Output

Both implementations will produce valid JSON that matches your intended structure (fixed for duplicate keys):

[
  {
    "model": "AAA",
    "name": "Nike Run",
    "sizes": [
      {
        "id": "101",
        "size": "9"
      },
      {
        "id": "102",
        "size": "10"
      },
      {
        "id": "100",
        "size": "11"
      }
    ]
  },
  {
    "model": "BBB",
    "name": "Adidas X",
    "sizes": [
      {
        "id": "103",
        "size": "11"
      }
    ]
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:25:01