The statements that produced the strange output is
$response = '{"17366":{"title":"title1","content":"content1"},"22747":{"title":"title2","content":"content2"}}';
$result = json_decode($response, true);
foreach ($result as $document => $details) {
echo "Title : {$details['title']}, ";
echo "content : {$details['content']} ";
echo '<br>';
}
//prints, this one ok
//Title : title1, content : content1
//Title : title2, content : content2
But if
$response = '{"title":"title1"}';
$result = json_decode($response, true);
foreach ($result as $document => $details) {
echo "Title : {$details['title']}, ";
echo "content : {$details['content']} ";
echo '<br>';
}
//prints
//Title : t, content : t
In this case, i know that the $details is not an array and it does not have such keys in it, if so it should have produced an exception or error. But it prints only the first letter of that string for both.
Anyone please points out what i’m doing wrong with those? or is that the behavior and i failed to assert something?
Because $details contains a string and not an array, the key ‘title’ is casted to int. (int)’title’ returns 0. $details[0] is ‘t’.
Prints out 0
Prints out ‘h’
Prints out ‘e’ because (int)’1title’ is casted to 1.