如何从JSON对象获取数据

时间:2022-12-04 16:01:07

When I have a normal array and multidimensional array in PHP and I return them like this

当我在PHP中有一个普通的数组和多维数组时,我会像这样返回它们

$data['normalArray'] = $array;
$data['multiArray'] = $multiArray;

echo json_encode($data);

How can I access them in jQuery? I tried using $.each but no results

如何在jQuery中访问它们?我尝试使用$ .each但没有结果

/edit Some extra info I'm using ajax to get the objects, and the normal one works now but not sure how to do the multidimensional array

/编辑一些额外的信息我正在使用ajax来获取对象,而正常的一个现在可以工作,但不知道如何做多维数组

success: function (result) 
                $.each(result.normalArray, function (i, item) {
                    console.log(item.key);
                });
            }

2 个解决方案

#1


2  

You've to parse the JSON String to object using JSON.parse().

您将使用JSON.parse()将JSON String解析为对象。

$.each() in jQuery is designed to loop through the DOM elements. You can also loop/iterate through Array of elements.

But first you need to parse the JSON string returned from PHP using JSON.parse(JSON_STRING)

jQuery中的$ .each()旨在循环遍历DOM元素。您还可以循环/遍历元素数组。但首先你需要使用JSON.parse(JSON_STRING)解析从PHP返回的JSON字符串

#2


0  

Try this code

试试这个代码

 $.getJSON('url',function(r){
           for($i=0;$i<=r.length;$i++){
               // your code with object r 
            }
        });    

#1


2  

You've to parse the JSON String to object using JSON.parse().

您将使用JSON.parse()将JSON String解析为对象。

$.each() in jQuery is designed to loop through the DOM elements. You can also loop/iterate through Array of elements.

But first you need to parse the JSON string returned from PHP using JSON.parse(JSON_STRING)

jQuery中的$ .each()旨在循环遍历DOM元素。您还可以循环/遍历元素数组。但首先你需要使用JSON.parse(JSON_STRING)解析从PHP返回的JSON字符串

#2


0  

Try this code

试试这个代码

 $.getJSON('url',function(r){
           for($i=0;$i<=r.length;$i++){
               // your code with object r 
            }
        });