0

I'm getting the "Warning: Illegal string offset" error when trying to extract data from an array I have converted from JSON.

Now I gather this happens when the index you are using does not exist, which puzzles me because it does exist and works fine when I wish to access the array value directly.

My JSON is decoded into the array using the code $clean = json_decode($json_output, true); and if I use echo $clean['text'] the string value of 'text' is displayed fine.

However when I attempt this piece of code I get the error:

foreach ($clean as $key => $list){
$output .= $list['text'];}

I have a feeling I am making a silly mistake somewhere!

1
  • Please Check The structure of array With print_r($clean); Commented Apr 27, 2013 at 17:52

2 Answers 2

1

With $list['text'] you are actually accessing the value of $clean['text'], which is apparently the string "text". Only, you're accessing it as if it were an associative array - actually exactly the same one as $clean. Try this:

foreach ($clean as $key => $list)
{
    if ($key === 'text')
    {// only echo for $clean['text']
        echo 'array clean, key: '.$key.' => '.$list."\n";
        continue;//next
    }
    echo $key.' => '.$list."\n";//shows all other key-value pairs
}

That should clear things up for you: $key will hold all keys that $clean holds, including text, $list will be assigned the value referenced by that key. It's as simple as that, really

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

3 Comments

Note that your answer is wrong! if $clean would be a string, then there would be a different error message: Warning: Invalid argument supplied for foreach()
@hek2mgl: I'm not saying $clean is a string, that's an associative array, $list is a string that the OP is accessing as if it were $clean... I was trying to be concise, but I'll edit, because I see why you might think I meant otherwise.
@hek2mgl: Sorry, but there's no point in adding "thanks hek2mgl for pointing out that my original answer was confusing". In essence, both say the same thing.
0

Seems that $list is a string rather than an array. Therefore $list['text'] fails. var_dump($list); inside the loop will help.

Note that var_dump() will be always your friend if you encounter such problems.

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.