0

It might sound like a bit of a weird question, but i've always struggled to understand the different structures of arrays and objects when passing them via JSON.

How would I build an array in PHP, and pass it back via JSON so that when i console log it out, it displays as a list of array objects like this?

console.log example

At the moment this is my code

    $users = [];
    foreach($users as $key => $user){
        $array = [];
        $array['username'] = $user->username;
        $array['id'] = $user->id;
        array_push($users, $array);
    }
    return response()->json(['list'=> $users]);

But this returns it so it looks like this

{list: [{username: 'Joe Bloggs', id: 1}, {username: 'John Smith', id 2}]}

in the console log.

How would i structure my php so that when I pass it back via JSON, and console log it out in the browser, it looks like the picture above? With a dropdown arrow, and an array of objects for me to click through?

The different types of arrays and objects always confuses me, and I kind of just do trial and error until it works the way I want, but I want to understand how it works.

I just cant seem to wrap my head around it!

EDIT

Just to add some extra information to try and get across what I am trying to do.

At the moment my javascript is console.log('Data Returned', result);.

In my PHP, if I grab a class in Laravel using

return response()->json(['list'=> User::all()]);

When I pass it back, it displays like the picture I have attached, with a dropdown and an array of objects.

If I then change the PHP to try and build the object myself before passing it back, and I change it to the above PHP code, it displays like this in the console log {list: [{username: 'Joe Bloggs', id: 1}, {username: 'John Smith', id 2}]} without me changing the javascript.

How do I manually build an object in PHP, so that when I pass it back, it console logs out like the picture above, with an array of objects and a dropdown to click through them all?

S_R
  • 1,818
  • 4
  • 27
  • 63
  • Do you mean the browser console ? – Bart Apr 05 '18 at 09:31
  • Yes, I want to build the array in PHP in a certain way so that when i console log it out in the browser console, it displays in the format of the picture – S_R Apr 05 '18 at 09:33
  • 1
    try console.log(JSON.stringify(data)); – Bart Apr 05 '18 at 09:34
  • This wouldn't work, as this would display the data as a string, not an array of objects. – S_R Apr 05 '18 at 09:36
  • 1
    did you click the `>` arrow showing before `Data returned - {list:Array}` ? @S_R – mith Apr 05 '18 at 09:37
  • My problem is that the way I am building it in PHP at the moment and passing it back via JSON does not give me the dropdown option. I want to be able to achieve it as a dropdown list, but I don't know how to build it in PHP so that when its passed back it has a dropdown. – S_R Apr 05 '18 at 09:39
  • Try console.dir instead of console.log – Bart Apr 05 '18 at 09:42
  • I'm sorry if i'm sounding confusing with this, but it is not a javascript issue when console logging it out, I want to build the php in a certain way, so that when I console log it out, it displays like this. – S_R Apr 05 '18 at 09:44
  • Show us the JS code you use to call the PHP. – RiggsFolly Apr 05 '18 at 09:48
  • But you're logging in the browser, so PHP has nothing to do with the way you log your data – Bart Apr 05 '18 at 09:48

2 Answers2

0

Yes, the above json returned by php is exactly what you want. Here, list is an array of objects. In your example you list array has two objects. You can access them through . or ['key'].

Suppose you assign your JSON response object to some variable json like below-

var json = response;
// now you can fetch name of first element by -
json.list[0].username;
// for the second username
json.list[1].username;

// you can iterate over the list like (forEach in javascript)
json.list.forEach(function(object,index){
      // this will print the username of each object stored as element in list array
      console.log(object.username);
     // suppose you have used jquery and your select has id="userId" then following line of code simply add them in your select list
     $('#userId').append('<option value="'+object.id+'">'+object.username+'</option>');
});

Remember array can be of any type - integer,array,objects,string. If array elements are like [1,2,3,4,5] then it's array of integer, if array elements are like ['some','words','goes','here','like','this'] then it's an array of strings. If array elements are like [[1,2,3],['some','words','here']] then it's array of array ... and your output above is array of objects.

feel free to ask question.

Veshraj Joshi
  • 3,544
  • 3
  • 27
  • 45
0

Lets say I have an data like:

{username: 'Joe Bloggs', id: 1} //JSON object notation

Standard PHP array:

$array = array(
   'username' => 'Joe Bloggs',
   'id'       => '1'
)

If that was stored as an array in a variable called $array, then I would access it like this in PHP:

 $array['username']  //Joe Bloggs

If it was stored as an object $object, then I would access it like this:

 $object->username //Joe Bloggs

In js the arrays are the similiar:

array['username'] //Joe Bloggs

But objects are like this:

object.username //Joe Bloggs

If I want to save a value to a variable in PHP:

$array['username'] = 'Joe Bloggs';

$object->username = 'Joe Bloggs';

And in js it is like this:

array['username'] = 'Joe Bloggs';
object.username = 'Joe Bloggs';

Now you just need to know if your dealing with an array or object. Js deals with alot of objects. The thing with objects is that you are really accessing properties of that object. Properties can be functions as well. If an object has a method/function say getId(). Then you can:

In PHP:

$object->getId();

And in js:

object.getId(); 

I probably butchered this really bad, but that the very basics.

Joseph_J
  • 3,654
  • 2
  • 13
  • 22