Roy Stijsiger
Roy Stijsiger

Reputation: 309

PHP json encode foreach only loops through the first item

So I'm busy at creating a system. That system generates a bit of JSON

For example:

{
    "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"
        }
    ]
}

Now im trying to get every "build" with a foreach in PHP this only loops the first time and then does nothing.

$i = 0;

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

Upvotes: 1

Views: 1229

Answers (3)

CodeGodie
CodeGodie

Reputation: 12132

You're working with an array of objects. This is how you should be doing it:

<?php

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

?>

Upvotes: 1

Hasse Bj&#246;rk
Hasse Bj&#246;rk

Reputation: 1601

This is a working version

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

First you need to use the json decoded object Builds to iterate through. This will give you objects to display, like $build->title

Upvotes: 0

Philipp
Philipp

Reputation: 15629

Because of the for loop, you don't need a counter.

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

The only reason for a counter would be, if you want to iterate over the item elements in your builds.

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

Upvotes: 1

Related Questions