在迭代json数组时为foreach()提供的参数无效

时间:2016-08-09 01:40:22

标签: php html json

我有这个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"}]

我想在我的表格中显示我的HTML页面,但是我有这个错误:

  

为foreach()提供的参数无效

这是我收到错误的代码部分:

<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>

cantidadturnos的 var_dump 是我放在上面的json。 谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

json采用JavaScript对象的形式。 PHP无法读取它所以它需要使用json_decode()解析json,如下所示:

$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"}]');

现在$cantidadturnos采用foreach可以使用的数组形式:

foreach ($cantidadturnos as $turno) {
    // do something
}