Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TuffRivers's avatar

Accessing JSON object with foreach

Hi all,

im super confused how i can access this json object that im sending to my view in laravel. I was reading a few places that i need to decode this json ($json = json_decode($json)) first but that gives me htmlspecial chars error. With json as this:

[{  
"ClientID":24,
"Name":"Client1",
"Balance1":null,
"Balance2":null
},
{  
"ClientID":25,
"Name":"Client2",
"Balance1":24,
"Balance2":0
}]

I tried a few variations of this @foreach statement but im lost how to enter this object!!

@foreach ($data->ClientID[0])

{{$clientID}}

@endforeach 
0 likes
36 replies
Cronix's avatar

I did this (copy/pasted your data and put it in quotes and assigned to a variable)

$data = '[{  
    "ClientID":24,
    "Name":"Client1",
    "Balance1":null,
    "Balance2":null
},
{  
    "ClientID":25,
    "Name":"Client2",
    "Balance1":24,
    "Balance2":0
}]';

$decoded = json_decode($data, true);

foreach($decoded as $d) {
    foreach($d as $k=>$v) {
        echo "$k - $v\n";
    }
}

output:

ClientID - 24
Name - Client1
Balance1 -
Balance2 -
ClientID - 25
Name - Client2
Balance1 - 24
Balance2 - 0
2 likes
Cronix's avatar

@jlrdw It's still json, you just have 2 arrays to iterate over in php...

1 like
jlrdw's avatar

One thing for sure iterating over json and array's can be tricky when you don't do it that often.

1 like
TuffRivers's avatar

OK so now i think i figured out what my question is lol..

How do i iterate over a 2 arrays?

@foreach ($clients as $client)

@foreach ($client as $attribute)

.......

@endforeach 

@endforeach 

I keep getting invalid argument ;S

jlrdw's avatar

Shouldn't that nested foreach work. It looks perfect.

1 like
Cronix's avatar

Depends, he didn't show all of his code. I tested mine with his actual data, and it works as I posted it in my first post. It's always hard to help when you don't get the complete picture (code).

2 likes
jlrdw's avatar

I liked it so much I copied and pasted and tested too. @Cronix just a quick side question how would you Loop through that in jQuery ajax. In mine it never likes the brackets.

jlrdw's avatar

I figured out something, this

"[{"dogname":"Belle","comments":"Yr old female. I was found at a rest stop, some tourist brought me here."},{"dogname":"Dale Evans","comments":"4 month female lab mix. Curious playful puppy."}] ◀"

With the brackets, a response like:

return Response::json($dog);   // did not work

But

echo json_encode($dog);  // Does work

But only if fetch mode is $sth->fetchAll(\PDO::FETCH_ASSOC);

Whole thing, just a test:

    public function testg() {
        $dogid = Request::input('somevar');
        $sql = "SELECT dogname, comments FROM dc_dogs WHERE dogid < :dogid";
        $params = ['dogid' => $dogid];
        $sth = DB::getPdo()->prepare($sql);
        $sth->execute($params);
        $dog = $sth->fetchAll(\PDO::FETCH_ASSOC);
        echo json_encode($dog);
    }

And the jquery:

    $(function () {
        $("#testme").click(function (event)
        {
            event.preventDefault();
            alert('hello');
            var somevar = '3';
            $.ajax({
                url: 'testg',
                type: 'GET',
                data: 'somevar=' + somevar,
                dataType: 'json',
                success: function (data) {
                    $.each(data, function (index, item) {
                        alert(item.dogname)

                    });
                },
                error: function (err) {
                    alert(err);
                }
            });

        });


    });

That's when a json array is passed with more that one item. But if a single array, then

return Response::json($dog);   // Does work

I cannot figure out why.

Cronix's avatar

@jlrdw Why do you keep cluttering up other peoples posts with your own questions?

1 like
jlrdw's avatar

@Cronix only because this one had to do with json as original question and I hoped it would help others as well, as some need to loop json responses in jquery as well.

I Have very rarely had a question in a question.

EDIT: If you want, I will delete all my stuff from this thread, but I was hoping for a good reply so anyone landing here could see json looping in not only php but javascript as well.

Cronix's avatar

But hardly anyone else is using PDO directly, they are using Eloquent models, and SomeModel::find(1)->toArray() gives an array instead of an object with an Eloquent model, but this has nothing to do with this post. Sometimes you make things too hard for yourself by not using Eloquent and using pdo directly and don't have all of the helper methods available to you.

And your json array you posted above doesn't work because you wrapped the whole thing in double quotes instead of single quotes, which won't work since the array itself uses double quotes.

1 like
TuffRivers's avatar

@Cronix I just want to say thank you for your patience with me, even in other threads, i appreciate your knowledge!

my controller

{
    public function index(){

    $balance = DB::select('CALL sp_GetBalance()');
 

    $json = json_encode($balance);
  

     return view('myview.index', compact('json'));

}

}

myview

@extends ('layouts.master')

@section ('content')

                 <table class="total-balance table mt-4">
                      <thead>
                        <tr>
                          <th>CLIENT</th>
                          <th>Balance</th>                                    
                        </tr>
                      </thead>
                      <tbody>
                      

                        @foreach ($json as $row)

                        @foreach ($row as $info)

                        <tr>
                          <td>{{$info->ClientID}}</td>
                          <td></td>                                    
                        </tr>   

                             @endforeach

                             @endforeach

                      </tbody>
                </table>

@endsection

my error: invalid argument foreach

Cronix's avatar

Yes, you can't iterate over json directly with php. You're json_encoding() it.

$json = json_encode($balance);
1 like
jlrdw's avatar

But hardly anyone else is using PDO directly, they are using Eloquent models

Ok I agree I should have started a new thread. But eloquent uses PDO directly.

I didn't put the double quotes, thats from a

$dogs = json_encode($dog);
dd($dogs);

Just to see what the array looked like. A

$somevar = SomeModel::find(1)->toArray()
$var2 = json_encode($somevar);
dd($var2);

Should also give the same quotation marks.

But it does work in the jquery. I am just wondering why

return Response::json($var2);

Doesn't work sometimes, as it should.

Cronix's avatar

Please post the output of this:

$balance = DB::select('CALL sp_GetBalance()');
dd($balance);
1 like
Cronix's avatar

@jlrdw return Response::json($dog);... you already json_encoded $dog, so it's trying to do it again there... $dog should be a php array using that scenario, not a json_encoded string.

1 like
jlrdw's avatar

No I don't use both, one or the other. I am going to try a model now to see if

return Response::json($dog);

works. It works with one result, I am saying with 2 or more results, I have to use

echo json_encode($dog);

// instead of

return Response::json($dog);

I am trying to troubleshoot the why it's not working with 2 or more results.

TuffRivers's avatar

I think i must be slow.

No matter what i do i cant iterate over this data.

if i try to convert it to a string, i cant get objects in a string with foreach

if i use json decode, i get html special chars error

i cant iterate over json object with php i get invalid argument foreach

Am i making this a lot harder than its supposed to be?

Cronix's avatar

Please show us the exact output of the query from the controller like I asked above.

1 like
TuffRivers's avatar

@Cronix sorry missed that between the other posts (lol)

from my dd($json) in controller

array:85 [▼
  0 => {#444 ▼
    +"ClientID": 64
    +"Name": "ACT "
    +"Soil Balance": 0.0
  }
  1 => {#445 ▼
    +"ClientID": 3092
    +"Name": "AXE"
    +"Soil Balance": 0.0
  }
  2 => {#446 ▼
    +"ClientID": 39
    +"Name": "RTF Inc."
    +"Soil Balance": 0.0
  }
  3 => {#447 ▼
    +"ClientID": 3079
    +"Name": "SDF"
    +"Soil Balance": 0.0
  }
  4 => {#448 ▼
    +"ClientID": 3111
    +"Name": "SQW"
    +"Soil Balance": 0.0
  }
]

hmm why cant i send that to my view as it is without html special char error?

Cronix's avatar

I was asking for dd($balance); not the json

1 like
TuffRivers's avatar

its same thing i just changed the variable becase i was testing it, i didnt actually convert that data to json before dd, sorry for confusion

jlrdw's avatar

Have you tried something like

    foreach($array as $i => $item) {
        echo $array[$i]['Name'];
    }

Replace $array with your variable name.

Edit: But probably won't work, I just saw it looks like a json array, sorry.

Cronix's avatar

I don't know what to say. My first post, where I used the data you originally posted and showed all of the code on how to do it, worked.

1 like
Nash's avatar

It looks like you have an array with objects. Set the second parameter of json_decode to true to convert the objects into associative arrays:

$arr = json_decode($json, true);
Cronix's avatar

It looks like you have an array with objects. Set the second parameter of json_decode to true to convert the objects into associative arrays:

Yes, like I showed in my first post lol

1 like
Nash's avatar

Yes, like I showed in my first post lol

@Cronix Exactly. It's just really easy to miss that second parameter and from the looks of it, that might just be what's missing.

TuffRivers's avatar

@Cronix @Nash haha im sorry i know im probably doing something wrong, but when i do that and send $arr to my view i get special chars error

let me test again to make sure, i will report back!

Cronix's avatar

it would help if you also posted your actual view code where you are looping and not skip things.

1 like
Next

Please or to participate in this conversation.