如何使用PHP拆分API返回JSON中DESCRIPTION字段的特定值?
Hey there! Let's tackle this problem step by step. You've already fetched and parsed the API response using GuzzleHttp and json_decode, so now we just need to split that DESCRIPTION field and restructure the data into your desired format. Here's a straightforward solution using foreach (the most natural fit for iterating over arrays in PHP):
Step-by-Step Implementation
First, let's assume you've already parsed the API response into an associative array (pass true as the second argument to json_decode to get an array instead of objects):
// 假设$apiJsonResponse是Guzzle返回的原始JSON字符串 $responseData = json_decode($apiJsonResponse, true); // 初始化最终的结果结构 $result = [ [ "CATEGORY" => "COUNTRIES", "LISTS" => [] ] ]; // 遍历每个返回的条目 foreach ($responseData as $countryItem) { // 用分号拆分DESCRIPTION字段,然后过滤掉空元素(因为末尾的分号会产生空字符串) $descriptionParts = array_filter(explode(';', $countryItem['DESCRIPTION'])); // 提取并清理国家代码和名称(拆分后的索引2是代码,索引3是名称,注意trim去掉多余空格) $countryCode = trim($descriptionParts[2]); $countryName = trim($descriptionParts[3]); // 将整理好的信息添加到LISTS数组 $result[0]['LISTS'][] = [ "NAME" => $countryName, "CODE" => $countryCode ]; } // 转换为格式化的JSON字符串,方便保存到日志 $finalJson = json_encode($result, JSON_PRETTY_PRINT); // 保存到日志文件(替换成你的日志路径) file_put_contents('countries.log', $finalJson);
Key Details Explained
explode(';', ...): Splits theDESCRIPTIONstring into an array using semicolons as separators.array_filter(): Removes empty elements from the split result (since the originalDESCRIPTIONends with a semicolon, which creates an empty string at the end of the array).trim(): Cleans up any leading/trailing whitespace from the extracted code and name (e.g., turns" US"into"US").JSON_PRETTY_PRINT: Ensures the output JSON is nicely formatted, making it easier to read in the log file.
Alternative: Using a for Loop
If you prefer a for loop instead (useful if you need explicit index control), here's how that would look:
$responseData = json_decode($apiJsonResponse, true); $result = [ [ "CATEGORY" => "COUNTRIES", "LISTS" => [] ] ]; $itemCount = count($responseData); for ($i = 0; $i < $itemCount; $i++) { $countryItem = $responseData[$i]; $descriptionParts = array_filter(explode(';', $countryItem['DESCRIPTION'])); $countryCode = trim($descriptionParts[2]); $countryName = trim($descriptionParts[3]); $result[0]['LISTS'][] = [ "NAME" => $countryName, "CODE" => $countryCode ]; } $finalJson = json_encode($result, JSON_PRETTY_PRINT); file_put_contents('countries.log', $finalJson);
Either approach will generate exactly the JSON structure you need, ready to be saved to your log file.
内容的提问来源于stack exchange,提问作者code_nameLuigi

