dongqigu0429 2012-09-17 10:25
浏览 43
已采纳

为什么我在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?

  • 写回答

3条回答 默认 最新

  • douwen4401 2012-09-17 10:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制