This is the 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));
?>
and I tried this
<?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>";
?>
although i am unable to succeeded
To perform a GET request on the route https://coderbyte.com/api/challenges/json/json-cleaning and then clean the object according to the following rules: Remove all keys that have values of N/A, -, or empty strings. If one of these values appear in an array, remove that single item from the array. Then console log the modified object as a string.
How to accomplish this?
CodePudding user response:
Try this
$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);
$newData = json_decode($data, true);
filterNAPlusEmptyStrings($newData);
function filterNAPlusEmptyStrings(&$newData) {
foreach ($newData as $key => $value ) {
if (is_array($value)) {
filterNAPlusEmptyStrings($value);
}
if ($value === '' || $value === 'N/A') {
unset($newData[$key]);
}
}
}
echo "<pre>" . print_r($newData, 1) . "</pre>";
CodePudding user response:
Can be done with recursive function as follow:
function clean_obj($data) {
if (is_array($data)) {
foreach ($data as $key => $val) {
if ($val == 'N/A' || $val == '-' || $val == '') {
unset($data[$key]);
}
if (is_array($val)) {
$data[$key] = clean_obj($val);
}
}
}
return $data;
}
$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);
$newData = json_decode($data, true);
$new_array=clean_obj($newData);
echo "<pre>" . print_r($new_array, 1) . "</pre>";