-2

I have JSON script that return some data but sometimes its empty and my foreach loop throws out an error when its empty here is my code

<?php
$planItems = getJSON('getPlanItems');
foreach ((array)$planItems->items as $item){
?>

I notice its because of

$planItems->items

Removing the -> doesnt throw out the error but then I cant read the result correctly from the JSON data.

Is there anyway to fix this?

6
  • is that a function getJSON? it looks like a javascript function. maybe take out that (array) Commented Oct 6, 2012 at 18:03
  • what is var_dump(getJSON('getPlanItems')); ?? Commented Oct 6, 2012 at 18:04
  • not its just a php function. removing (array) causes the same error. Which is Notice: Trying to get property of non-object Commented Oct 6, 2012 at 18:05
  • 2
    What would happen, if you check if that JSON script has returned empty data, before you start iterating over it? Commented Oct 6, 2012 at 18:06
  • 1
    Did you look at: stackoverflow.com/questions/1699924/… Commented Oct 6, 2012 at 18:09

3 Answers 3

2

Of course it errors when $planItems->items isn't set or is not an array. It's not very convenient, but that's what foreach does. To prevent it, you need to check before looping, e.g.:

if (isset($planItems->items) && is_array($planItems->items)) {
    foreach ($planItems->items as $item) {
        // ....
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

wrong: casting to array works fine for the many other cases, too.
But why would you want to cast to array? Either it is an array already, in which case you can iterate; or it's not, in which case iterating doesn't make sense. Casting to array may work, but it doesn't really communicate the intention - we don't want to convert anything, really; we want to iterate if and only if that particular value exists and is an array.
Yea I was thinking of checking the array, but I though there could be an easier way. Since I have lots of foreach loops
@tdammers: The op wanted to. I think it should be more clearly worded and better pointed to: stackoverflow.com/a/12762442/367456
1

You've got a good nose, indeed the problematic part is:

$planItems->items

This would only work if $planItems is an object and has the items member. You need to check that first, most likely you have missed to check the return value from getJSON for the error conditions.

$planItems = getJSON('getPlanItems');

if ($planItems === ???) { # do your error condition checking here
    throw new UnexpectedValueException('Remove Json Request error.');
}

If you add proper error handling to your code, the problems will disappear.

6 Comments

so something like dev suggested to check if array is empty? if (!empty($planItems )) or check if array is bigger then 0?
That would not cause you any problems with foreach. But anyway, at the foreach it is too late. You need to check the post-conditions after you've call getJSON. Do the error checking first. If getJson does remote interaction, what do you do when remote is down or not reachable? What will the function return?
if(count($array) > 0 seems to work fine like someone suggested. I was hoping that would be an easier way. I dint want to add if(count($array) > 0 to all my foreach but I guess there is no other way
No you do not need. If $array is an array and count of it is 0, then foreach would have 0 iterations. Ergo: You do not need to care about that case.
Sorry I dont understand what you mean. My function gets the file content using file_get_contents of a php script that returns encode json.Then my function returns the decode json. So then my script if (count($planItems)>0){ foreach ($planItems->items as $item) SO if array is bigger then 0 it will run the loop else I do something else. Im still confused why is it that I dont need count
|
0

You can convert JSON to Array using json_decode PHP function with second parameter true. and then before foreach write condition if (!empty($planItems ))

It would be

<?php
$planItems = json_decode(getJSON('getPlanItems'),true);
if (!empty($planItems['items'] ))
foreach ($planItems['items'] as $item){
?>

4 Comments

my function already returns a decoded json. I will try the if (!empty($planItems ))
if that is already decoded, you should not parse to array in foreach. also you are using that like a object like ->items, Good Luck.
$planItems['items'] doesnt seem to work throws out an error Fatal error: Cannot use object of type stdClass as array
That 's because you are not using json_decode and your function is doing that. I don't know, how ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.