将JSON数据作为控制台日志中的数组下拉列表返回

时间:2018-04-05 09:28:25

标签: javascript php json oop

这可能听起来像是一个奇怪的问题,但是当我通过JSON传递它们时,我总是很难理解数组和对象的不同结构。

我如何在PHP中构建一个数组,并通过JSON将其传回,这样当我将其注销时,它会显示为像这样的数组对象列表?

console.log example

目前这是我的代码

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

但这会返回它,所以它看起来像这个

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

在控制台日志中。

我如何构建我的php,以便当我通过JSON传回它,并且控制台在浏览器中将其记录下来时,它看起来像上面的图片?使用下拉箭头和一组对象供我点击?

不同类型的数组和对象总是让我感到困惑,我只是按照我想要的方式进行试验和错误,但我想了解它是如何工作的。

我似乎无法绕过它!

修改

只是添加一些额外的信息,试图了解我想要做的事情。

目前我的javascript是console.log('Data Returned', result);

在我的PHP中,如果我使用

在Laravel中获取一个类

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

当我将它传回时,它会显示我附上的图片,下拉列表和一组对象。

如果我然后更改PHP以尝试在传回之前自己构建对象,并将其更改为上面的PHP代码,它在控制台日志{list: [{username: 'Joe Bloggs', id: 1}, {username: 'John Smith', id 2}]}中显示如下,而不更改javascript。

如何在PHP中手动构建一个对象,以便在我将其传回时,它会像上面的图片一样注销,有一组对象和一个下拉列表来点击它们全部?

2 个答案:

答案 0 :(得分:0)

是的,php返回的上述json正是你想要的。这里,list是一个对象数组。在您的示例中,list数组有两个对象。您可以通过.['key']

访问它们

假设您将JSON响应对象分配给某个变量json,如下所示 -

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

记住数组可以是任何类型 - 整数,数组,对象,字符串。如果数组元素是 [1,2,3,4,5] 那么它是整数数组,如果数组元素像 ['some','words','goes', 'here','like','this'] 然后它是一个字符串数组。如果数组元素像 [[1,2,3],['some','words','here']] 那么它是数组的数组......而你上面的输出是数组对象。

随时提问。

答案 1 :(得分:0)

假设我有一个类似的数据:

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

标准PHP数组:

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

如果它作为一个数组存储在一个名为$ array的变量中,那么我会在PHP中这样访问它:

 $array['username']  //Joe Bloggs

如果它存储为对象$ object,那么我会像这样访问它:

 $object->username //Joe Bloggs

在js中,数组类似:

array['username'] //Joe Bloggs

但是对象是这样的:

object.username //Joe Bloggs

如果我想将值保存到PHP中的变量:

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

$object->username = 'Joe Bloggs';

在js中就是这样:

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

现在您只需要知道您是否处理数组或对象。 Js处理很多对象。有对象的东西是你真正访问该对象的属性。属性也可以是函数。如果一个对象有一个方法/函数,请说getId()。然后你可以:

在PHP中:

$object->getId();

在js:

object.getId(); 

我可能认为这非常糟糕,但这是非常基础。