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 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?