PHP json编码foreach只循环第一项

时间:2015-11-12 19:12:46

标签: php json

所以我正忙着创建一个系统。 该系统会生成一些JSON

例如:

{
    "Builds": [
        {
            "title": "test",
            "item1": "3",
            "item2": "3",
            "item3": "0",
            "item4": "0",
            "item5": "0",
            "item6": "0"
        },
        {
            "title": "test2",
            "item1": "3",
            "item2": "3",
            "item3": "2",
            "item4": "0",
            "item5": "0",
            "item6": "0"
        }
    ]
}

现在我试图用PHP中的foreach获取每个“build”,这只是第一次循环,然后什么也不做。

$i = 0;

foreach($builds as $build){
    //echo $i;
    echo $build[$i]['title'];
    echo '<img src="' . $build[$i]['item1'] . '" alt=""></img>';
    $i++;
}

3 个答案:

答案 0 :(得分:1)

由于for循环,您不需要计数器。

$json = '{"Builds":[{"title":"test","item1": "3","item2": "3","item3": "0","item4": "0","item5": "0","item6": "0"},{"title":"test2","item1": "3","item2": "3","item3": "2","item4": "0","item5": "0","item6": "0"}]}';
$data = json_decode($json, true);
$builds = $data['Builds'];
foreach($builds as $build){
    echo $build['title'];
    echo '<img src="' . $build['item1'] . '" alt=""></img>';
}

如果你想迭代构建中的item元素,那么计数器的唯一原因就是。

for ($i = 1; isset($build['item' . $i]); $i++) {
    echo '<img src="' . $build['item' . $i] . '" alt=""></img>';
}

答案 1 :(得分:1)

您正在处理一系列对象。这就是你应该这样做的方式:

<?php

$json = ""; //your JSON string
$obj = json_decode($json);
foreach ($obj->Builds as $build) {
    echo $build->title;
    echo "<img src='$build->item1' alt=''>";
}

?>

答案 2 :(得分:0)

这是一个有效的版本

$builds = '{"Builds":[{"title":"test","item1": "3","item2": "3","item3": "0","item4": "0","item5": "0","item6": "0"},{"title":"test2","item1": "3","item2": "3","item3": "2","item4": "0","item5": "0","item6": "0"}]}';

foreach(json_decode( $builds )->Builds as $build ){
    echo $build->title;
    echo '<img src="' . $build->item1 . '" alt=""></img>';
}

首先,您需要使用json解码对象Builds进行迭代。这将为您提供显示对象,例如$build->title