douxian4376 2016-09-25 07:50
浏览 127
已采纳

为什么这个PHP foreach不会遍历从json字符串获取信息的数组中的每个项目?

I have this json string that it's stored as text in a mysql database (I have that in a "cronograma" field).

This is what $row['cronograma'] outputs:

{"fecha":["02 enero","05 enero","20 enero","22 enero","25 enero"],"bolilla":["22","26","15","28","33"],"docente":["Juan","Pedro","Lidia","Maxima","Luis"]}

And I want to extract the information from it, and presented it in screen.

This is how I extract the information with json_decode() and loop through it with a foreach:

    $cronograma = json_decode($row['cronograma'], true);
    $cant = count($cronograma['fecha']);
    echo $cant.'<br>'; //this outputs 5
    $i = 0;
      foreach ($cronograma as $key => $value) {
          echo $i;
          $fecha = $cronograma['fecha'][$i];
          $bolilla = $cronograma['bolilla'][$i];
          $docente = $cronograma['docente'][$i];

          echo "<b>Fecha:</b> $fecha <b>Bolilla:</b> $bolilla <b>Docente:</b> $docente<br>";

          if ($i < $cant) $i++;
      }  

Now, my problem is that it won't output the five items in the array, but just three, and I don't understand why. Even if I change ($i < $cant) to ($i < 5), it still outputs only 3.

This is the output:

0Fecha: 02 enero Bolilla: 22 Docente: Juan

1Fecha: 05 enero Bolilla: 26 Docente: Pedro

2Fecha: 20 enero Bolilla: 15 Docente: Lidia

And this is what it should be:

0Fecha: 02 enero Bolilla: 22 Docente: Juan

1Fecha: 05 enero Bolilla: 26 Docente: Pedro

2Fecha: 20 enero Bolilla: 15 Docente: Lidia

3Fecha: 22 enero Bolilla: 28 Docente: Maxima

4Fecha: 25 enero Bolilla: 33 Docente: Luis

What am I missing?

展开全部

  • 写回答

3条回答 默认 最新

  • doude4201 2016-09-25 08:16
    关注

    Because $cronograma contains 3 items; fecha, bolilla & docente, so I recommend changing your loop like:

        $cronograma = json_decode($row['cronograma'], true);
        $cant = count($cronograma['fecha']);
        echo $cant.'<br>'; //this outputs 5
    
          for ($i = 0; $i < $cant; $i++) {
              echo $i;
              $fecha = $cronograma['fecha'][$i];
              $bolilla = $cronograma['bolilla'][$i];
              $docente = $cronograma['docente'][$i];
    
              echo "<b>Fecha:</b> $fecha <b>Bolilla:</b> $bolilla <b>Docente:</b> $docente<br>";
          }  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部