检索和使用json关联数组

Retrieving and using a json associative array

本文关键字:关联 数组 json 检索      更新时间:2023-09-26

我使用jquery和ajax来检索php中创建的动态数组,如下所示:

$json = array();
while ($row = $stmt->fetch_assoc()) {
    $json['item_'.$row['id']] = $row['name'];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($json);
exit;
如果我在浏览器中测试php文件,它输出:
{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}

到目前为止一切顺利。但如何在jquery中使用这个数组呢?

我有这个jquery ajax:
$.getJSON( "json.php", function(data) {
    console.log(data);
});

在浏览器中测试这个页面,它把这个放到控制台:

Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"}

这没关系,对吗?或者item_x也应该加引号吗?

现在,我如何在jquery中使用该数组?

如果我尝试console.log(data[0])它会显示undefined

正如我在注释中提到的,php关联数组变成了javascript对象,不能以数字方式访问。

一个解决方案是发送一个对象数组:

while ($row = $stmt->fetch_assoc()) {
    $json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}

data[0].key;
data[0].value;

EDIT在这个例子中显然是一个误导人的名字,最好用别的名字:

$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;

尝试使用$.each()来遍历该对象,

$.each(data,function(key,val){
  console.log(key,val);
});

演示

如果您想访问它而不迭代它,那么只需使用bracket notation

data['item_3'] //Simon

或者直接访问,比如

data.item_3 //Simon

然后把它转换成数组,就像这样,

var obj = {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"};
var convertedArray = $.map(obj,function(val,key){
    var obj = {}; obj[val] = key;
    return obj;
});
演示