0

I have a json array (dataArray) sent from js to php using JSON.stringuify.

I'm getting the output after using json_decode that object like this:

$resp = json_decode($dataArray,true);
error_log($resp);

Log:

[{"id":"0","name":"JOAO"},{"id":"1","name":"TONI"},{"id":"2","name":"ANA"}]

I'm trying to get the id and name values from each element in that array.

Using foreach returns an error since the object is not considered as an array... So I tried casting it to an array and then use it in the foreach, and it's size is still 1:

$arr = (array) $res;
error_log(sizeof($arr[0]));
foreach ($arr[0] as $dt) {
    error_log($dt);
}

This returns the "full sized 1 array"

[{"id":"0","name":"JOAO"},{"id":"1","name":"TONI"},{"id":"2","name":"ANA"}]

and if I try error_log($dt->id) I don't get any results...

I'm not understanding why this is not being considered as an array.

4
  • 1
    If you're managing to call error_log (which expects a string) without any issues, it sounds like your data might be double-encoded? Try json_decode(json_decode($dataArray),true); Commented Apr 20, 2020 at 15:59
  • 1
    What does var_dump($resp) show? Commented Apr 20, 2020 at 16:02
  • Or just show what $dataArray contains. Commented Apr 20, 2020 at 16:06
  • dataArray contains exacty that array Commented Apr 20, 2020 at 16:13

2 Answers 2

2

Seems you need the html_entity_decode() before decoding it,

$data = html_entity_decode($dataArray);
$output = json_decode($data,true);
foreach ($output as $key=>$dt) {
    echo "id=".$dt['id']," & name=".$dt['name'].PHP_EOL;
}
Sign up to request clarification or add additional context in comments.

Comments

0

If do as suggested:

$data = html_entity_decode($dataTypesArray);
$output = json_decode($data,true);

//or json_decode(json_decode($dataArray),true);
error_log($output);

foreach ($output as $dt) {
    error_log($dt);
}

I get error_log() expects parameter 1 to be string, array given so I used error_log(json_encode($dt)); I now I get the individual jsons but still no sucess logginf the ID and name...

1 Comment

have a look on my answer again, I've edited it to log the id and name value.

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.