<?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);
$newdata = json_decode($data,true);
foreach ($newdata as $key => $value) {
if(is_array($value))
{
foreach ($value as $about => $ddata) {
if($ddata == "" || $ddata == 'N/A' || $ddata == '-' )
{
unset($value[$about]);
}
}
}
else{
if($value == "" || $value == 'N/A' || $value == '-' )
{
unset($newdata[$key]);
}
}
}
var_dump($newdata);
curl_close($ch);
?>
Have you tried including the trim() function in your comparison ?
if(trim($ddata) == "" || trim($ddata) == 'N/A' || trim($ddata) == '-' )
yes i have. Might the issue be that this is an object and not an array ?
I don’t have enough knowledge on parsing json object data to be able to advise.
I assume that if the foreach loop is iterating through $newdata then it is reading $value and/or $ddata as a text field? Have you been able to confirm this with a quick gettype() check?
Worth mentioning that one thing that had me pulling my hair out once was the fact that a string I thought had spaces in, were not actually spaces, and instead were some other weird character.
/Danny
Maybe something like this will help?
<?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);
$newdata = json_decode($data, true);
echo "<pre>" . print_r($newdata, 1) . "</pre>";
foreach ($newdata as $key => $value) {
//echo "<pre>" . print_r($key, 1) . "</pre>";
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>";
I would imagine if the array gets nested again that you would need to have to play around with recursive array functions? Though there might be a better way in doing this in curl? Though I a not familiar with curl.