Rosamunda Rosamunda - 2 months ago 7
JSON Question

Why this PHP foreach wont loop through every item in an array that got the information from a json string?

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?

Answer

You just need a while loop to go through $cant

<?php

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

$cronograma = json_decode($cronograma, true);
$cant = count($cronograma['fecha']);
echo $cant.'<br>'; //this outputs 5
$i = 0;

while ($i < $cant){
    $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>";

    $i++;
}
Comments