我有这个对象:
{"15":{"id":15,"name":"Termostato","wiring_pi_pin":11,"is_local":0}}
对象来自此自编API
foreach ($gpio as $object) {
$temp['id'] = $object->id;
$temp['name'] = $object->name;
$temp['wiring_pi_pin'] = $object->wiring_pi_pin;
$temp['is_local'] = $object->is_local;
$api[$object->id] = $temp;
}
header('Content-Type: application/json');
echo json_encode($api);
我用这段代码读了它(我需要键和值):
$.getJSON(url, function(result) {
$.each(result, function(key,value) {
$.each(value, function(subkey,subvalue) {
console.log(subkey +' is ' + subvalue);
});
});
});
是否可以在PHP中简化,或者在JS中简化?
非常感谢
答案 0 :(得分:0)
没有必要将对象转换为关联数组,因为JSON以相同的方式表示它们。因此,您唯一需要做的就是创建一个使用$object->id
作为键的顶级关联数组。
foreach ($gpio as $object) {
$api[$object->id] = $object;
}
header('Content-Type: application/json');
echo json_encode($api);