我不能使用循环获取json数组值(PHP)

时间:2016-11-07 07:30:04

标签: php json

我有1个json,但我无法使用for循环

获取值
$string = [{"lt":"1","lot":["1","1","1","1","1"]},{"lt":"2","lot":["0","0","0","0","0"]},{"lt":"3","lot":["0","0","0","0","0","0"]}]
$json = json_decode($string,true);
for($i = 0;$i<count($json);$i++){
    for($j = 0;$j<count($json->lot);$i++){
        if($json->lot==0){
            echo $j;
        }
    }
}

我收到此错误:尝试获取非对象的属性

3 个答案:

答案 0 :(得分:0)

编辑您的代码:

$json = [{"lt":"1","lot":["1","1","1","1","1"]},{"lt":"2","lot":["0","0","0","0","0"]},{"lt":"3","lot":["0","0","0","0","0","0"]}]
$json = json_decode($json);
for($i = 0;$i<count($json);$i++){
    for($j = 0;$j<count($json->lot);$i++){
        if($json->lot==0){
            echo $j;
        }
    }

使用php json_decode()将json更改为在数组中解码。 json_decode

答案 1 :(得分:0)

您需要在json上使用json_decode。另外,请记住,json必须在PHP中存储为字符串。

<?php
$json = ['{"lt":"1","lot":["1","1","1","1","1"]}','{"lt":"2","lot":["0","0","0","0","0"]}','{"lt":"3","lot":["0","0","0","0","0","0"]}'];

foreach($json as $data) {
    $current = json_decode($data);

    foreach($current->lot as $lot)
        echo $lot;
}

答案 2 :(得分:0)

使用json_decode()函数进行解码json

<?php
$json = '[{"lt":"1","lot":["1","1","1","1","1"]},{"lt":"2","lot":["0","0","0","0","0"]},{"lt":"3","lot":["0","0","0","0","0","0"]}]';
$json = json_decode($json);
foreach($json as $val){
    foreach($val->lot as $lot) {
        if($lot==0){
            echo $lot;
        }
    }
}
?>