douxian4376 2016-09-25 15:50
浏览 126
已采纳

为什么这个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 16: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条)

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 如何用visual studio code实现html页面
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?