jimothy
jimothy

Reputation: 13

Array shows but subarray shows "illegal string offset" error - PHP

Here's a sample of

$arr = json_decode('{"people":[
{
  "id": "8080",
  "content": "foo",
  "member": [123, 456],
  "interval": 7
},
{ 
  "id": "8097",
  "content": "bar",
  "member": [1234, 4567],
  "interval": 7
}


]}', true);

$searchId = 123;
$results = array_filter($arr['people'], function($people) use ($searchId) {
    return in_array($searchId, $people['member']);
});

$final = json_encode($results);

echo $final;

This prints [{"id":"8080","content":"foo","member":[123,456],"interval":7}]

But when I try to get the specific value of an element (e.g. "content"), it shows me an illegal string offset error

echo $final["content"];

What should I be doing instead to show the value of "content"? (which would be "foo" in this case)

Upvotes: 1

Views: 53

Answers (2)

Zar Ni Ko Ko
Zar Ni Ko Ko

Reputation: 352

Actually , you don't need to $final = json_encode($results);

directly output to

echo $results[0]["content"];

Upvotes: 0

LF-DevJourney
LF-DevJourney

Reputation: 28529

Change echo $final["content"]; to echo $results[0]["content"];

Upvotes: 1

Related Questions