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

如何通过PHP实现对指定API的GET请求及JSON对象清理?

Problem Description

I need to complete the following task: Send a GET request to the endpoint https://coderbyte.com/api/challenges/json/json-cleaning, then clean the returned JSON object according to these rules:

  • Remove any keys whose values are N/A, -, or empty string.
  • If an array contains any of these values, remove the corresponding elements.
  • Finally, convert the modified object to a string and output it.

Existing Practice Code

<?php 
$ch = curl_init('https://coderbyte.com/api/challenges/json/json-cleaning'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
$data = curl_exec($ch); 
curl_close($ch); 
print_r(json_decode($data, true)); 
?>

My Unsuccessful Attempt

<?php 
$ch = curl_init('https://coderbyte.com/api/challenges/json/json-cleaning'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
$data = curl_exec($ch); 
curl_close($ch); 
print_r(json_decode($data, true)); 
echo "<pre>" . print_r($newdata, 1) . "</pre>"; 
foreach ($newdata as $key => $value) { 
    if (!is_array($value)) { 
        echo "key: " . $key . " Value: " . $value . "<br>"; 
        if (!empty($value) && $value !== "-" && $value !== "N/A") { 
            $new_array[$key] = $value; 
        } 
    } else { 
        foreach ($value as $k => $v) { 
            if (!empty($v) && $v !== "-" && $v !== "N/A") { 
                $new_array[$key][$k] = $v; 
            } 
        } 
    } 
} 
echo "<pre>" . print_r($new_array, 1) . "</pre>"; 
?>

How can I complete this task?


Solution

First, let's break down the issues in your attempted code:

  • You never assigned the decoded JSON to $newdata (you only printed it), so the loop had no data to process.
  • Array processing left gaps in indices (not a critical error, but messy).
  • The logic didn't account for potential nested structures (though the API response may not have them, it's good practice to handle this).

Here's a corrected, robust version of the code:

<?php
// Fetch the JSON data from the endpoint
$ch = curl_init('https://coderbyte.com/api/challenges/json/json-cleaning');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

// Decode JSON string to an associative array
$originalData = json_decode($data, true);

/**
 * Recursively cleans data by removing unwanted values
 * @param array $data The input array to clean
 * @return array The cleaned array
 */
function cleanData($data) {
    $cleaned = [];

    foreach ($data as $key => $value) {
        // Handle non-array values first
        if (!is_array($value)) {
            // Skip values that match our unwanted criteria
            if ($value === 'N/A' || $value === '-' || $value === '') {
                continue;
            }
            $cleaned[$key] = $value;
        } else {
            // Filter unwanted elements from arrays
            $filteredArray = array_filter($value, function($item) {
                return $item !== 'N/A' && $item !== '-' && $item !== '';
            });
            // Reindex the array to remove gaps from filtered elements
            $reindexedArray = array_values($filteredArray);
            // Only add the array to cleaned data if it's not empty
            if (!empty($reindexedArray)) {
                $cleaned[$key] = $reindexedArray;
            }
        }
    }

    return $cleaned;
}

// Process the original data
$cleanedData = cleanData($originalData);

// Convert cleaned array back to JSON string and output
echo json_encode($cleanedData, JSON_PRETTY_PRINT);
?>

Key Improvements:

  • Proper Data Assignment: We store the decoded JSON in $originalData so we can actually process it.
  • Recursive Cleaning: The cleanData function handles both top-level keys and nested arrays, making the code flexible for any JSON structure.
  • Clean Array Handling: array_filter removes unwanted elements, and array_values reindexes arrays to eliminate gaps left by removed items.
  • Explicit Value Checks: We directly compare against the exact unwanted values instead of relying on empty(), which avoids accidentally filtering out valid falsy values like 0.
  • Final Output: We use json_encode with JSON_PRETTY_PRINT to output a readable JSON string, which meets the requirement of converting the modified object to a string.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:42:33