PHP如何从API返回的JSON中提取指定水果列表
解决方案:精准提取水果列表并格式化输出
Got it, let's fix this up for you! The issue with your current code is that it's pulling all NOTES values into your list—including the agriculture header, fruit category label, and animal entries. We need to add logic to target only the fruit items between the fruit category marker and the next category.
核心思路
Your API response structures categories like this:
Category label (e.g.,
"Fruit Name; List of Fruits;") → category items → next category label
We'll:
- Flag when we enter the fruit section
- Capture only items in that section
- Stop capturing once we hit the next category
修正后的代码
// Assume $json_response is your raw API response string $response_body = json_decode($json_response, true); $fruitItems = []; $inFruitSection = false; foreach ($response_body as $item) { $notes = $item['NOTES']; // Trigger start of fruit section when we hit the fruit category label if (str_contains($notes, 'List of Fruits')) { $inFruitSection = true; continue; // Skip the category label itself } // Stop when we reach the next category (animal section) if ($inFruitSection && str_contains($notes, '; List of')) { break; } // Add to fruit list only if we're in the correct section if ($inFruitSection) { $fruitItems[] = ['FRUITS' => $notes]; } } // Build your desired output structure $finalOutput = [ [ 'NOTE_NO.' => '001', 'CATEGORY' => 'FRUITS', 'LISTS_TO_BUY' => $fruitItems ] ]; // Print formatted JSON (use JSON_PRETTY_PRINT for readability) echo json_encode($finalOutput, JSON_PRETTY_PRINT);
代码说明
$inFruitSection: A boolean flag to track if we're iterating through fruit items- We skip the category label (e.g.,
"Fruit Name; List of Fruits;") since it's not an actual fruit - We break out of the loop once we hit the animal category to avoid capturing irrelevant items
- Only items in the fruit section get added to
$fruitItems
输出结果
You'll get exactly the format you wanted:
[ { "NOTE_NO.": "001", "CATEGORY": "FRUITS", "LISTS_TO_BUY": [ { "FRUITS": "Apple" }, { "FRUITS": "Orange" }, { "FRUITS": "Grapes" }, { "FRUITS": "Mango" } ] } ]
内容的提问来源于stack exchange,提问作者code_nameLuigi
相关产品推荐
相关产品推荐

