为什么我在foreach循环中得到奇怪的输出?

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'.

echo (int)'title';

Prints out 0

$string = "hello world";
echo $string['title'];

Prints out 'h'

$string = "hello world";
echo $string['1title'];

Prints out 'e' because (int)'1title' is casted to 1.

As details is a string if you use the [] syntax on it you select the character from the string at that positon. Selecting a character at position 'title' or 'details' doesn't actually produce an error, instead PHP handles it as though you are selecting the first character i.e. $details[0].

Just add in a check to make sure details is an array:

if (is_array($details))
{
   // stuff here
}

It prints the first letter because it's trying to cast the associated key to a integer index.

So when PHP cast a string to integer usually return 0 unless the first character of the string it's a number.

By the other way as your code is trying to access to a string using indexes then PHP will return the Ncharacter of string specified by the index.

Mixing all:

$details = "title";

$details['content'] > $details[(int) 'content'] > $details[0]

$details[0] > "t"

$details[1] > "i"