0

i have an array like this which i got from parsing the html source:

Array
(
    [0] => 12345
    [1] => 54321
    [2] => 32546
    [3] => 98754
    [4] => 15867
    [5] => 75612
)

if I put it in a variable and run a foreach loop prefixing a url like so:

$x = Array;
foreach ($x as $y){
$r = 'http://example.com/' . $y;
echo $r . '<br>';
}

It will output like this:

http://example.com/12345
http://example.com/54321
http://example.com/32546
http://example.com/98754
http://example.com/15867
http://example.com/75612

and each of those output url if run in the browser will output an object EITHER like this:

{
   "key1": "value1",
   "key2": "value2",
   "key3": "value3"
}

OR like this:

{
   "error": {
      "errorMessage": "errorMessageValue",
      "errorType": "errorTypeValue"
   }
}

so my question is... how do I filter the Array in php so that it will only give me an Array that has a valid key/value pair and not the error object.

as suggested, I tried the following:

$x = Array;
foreach ($x as $y){
$link = 'http://example.com' . $y;
$json = file_get_contents($link);
$array = array_filter((array)json_decode($json), "is_scalar");
echo '<pre>';
echo json_encode($array) . '<br>';
echo '</pre>';
}

but it still output the same array and does not exclude the error object.

1
  • 1
    Please add addition information, where you produce that array? Commented Jul 27, 2013 at 0:35

2 Answers 2

4
$array = array_filter((array)json_decode($json), "is_scalar");

This will exclude all the objects from the array and you only have key => value pairs where value is nor an object nor an array.

Sign up to request clarification or add additional context in comments.

8 Comments

json_decode return an object unless the second argument is set to true
@Martin okay, added array cast ;-)
@bwoebi using your code, i get Notice: Array to string conversion when trying to use file_get_contents to get $json to work then echoing $array
if you want to output my array / store it somewhere, you have to re-encode it with json_encode($array).
@bwoebi it still output the same array as I had in the original. it did not exclude the error object.
|
0

Maybe I'm missing something, but can't you just check if the returned object contains an "error" entry and, if it does, skip it?

$x = Array;
foreach ($x as $y){
  $link = 'http://example.com' . $y;
  $json = file_get_contents($link);
  $returned_data = json_decode($json, true);

  // If returned data contains an "error" entry, just move to next one
  if(isset($returned_data['error'])) {
    continue;
  }
  echo '<pre>';
  echo json_encode($returned_data) . '<br>';
  echo '</pre>';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.