0

I have this json:

[{"nombre":"Example1","idcomplejo":"1","canchafk":"1","cantidadturnos":"35"},
{"nombre":"Example2","idcomplejo":"3","canchafk":"6","cantidadturnos":"29"},
{"nombre":"Example3","idcomplejo":"4","canchafk":"7","cantidadturnos":"6"},
{"nombre":"Example4","idcomplejo":"5","canchafk":"8","cantidadturnos":"4"},
{"nombre":"Example5","idcomplejo":"5","canchafk":"9","cantidadturnos":"2"}]

I wanna show in my table into my HTML page, but I have this error:

Invalid argument supplied for foreach()

This is the part of code where I getting the error:

<table cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th>ID Complejo></th>
            <th># Cancha></th>
            <th>Cantidad Turnos></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($cantidadturnos as $turno): ?>
        <tr>

            <td><?= h($turno->idComplejo) ?></td>
            <td><?= h($turno->canchaFK) ?></td>
            <td><?= h($turno->cantidadTurnos) ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

the var_dump of cantidadturnos is the json that i put above. Thanks for help

Federick Jons
  • 33
  • 2
  • 7
  • 2
    Possible duplicate of [How do I extract data from JSON with PHP?](http://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – scrowler Aug 09 '16 at 01:42
  • [`json_encode`](http://php.net/manual/en/function.json-encode.php) - closing as a duplicate – scrowler Aug 09 '16 at 01:42

1 Answers1

1

The json is in the form of a JavaScript object. PHP cannot read it so it needs to parse the json with json_decode(), like this:

$cantidadturnos = json_decode('[{"nombre":"Example1","idcomplejo":"1","canchafk":"1","cantidadturnos":"35"},
{"nombre":"Example2","idcomplejo":"3","canchafk":"6","cantidadturnos":"29"},
{"nombre":"Example3","idcomplejo":"4","canchafk":"7","cantidadturnos":"6"},
{"nombre":"Example4","idcomplejo":"5","canchafk":"8","cantidadturnos":"4"},
{"nombre":"Example5","idcomplejo":"5","canchafk":"9","cantidadturnos":"2"}]');

Now $cantidadturnos is in the form of an array the foreach can work with like this:

foreach ($cantidadturnos as $turno) {
    // do something
}
Robert
  • 10,126
  • 19
  • 78
  • 130