我有一个像这样的简单值对数组:
array(4) (
[4] => (string) Barcelona
[3] => (string) Cordoba
[1] => (string) Granada
[2] => (string) Jaen
)
我需要将其编码为JSON以响应以下格式的AJAX请求:
[{"pk": 4, "name": "Barcelona"},
{"pk": 3, "name": "Cordoba"},
{"pk": 1, "name": "Granada"},
{"pk": 2, "name": "Jaen"}]
如果我使用:
json_encode($a)
我得到以下内容:
{"4":"Barcelona","3":"Cordoba","1":"Granada","2":"Jaen","0":"Select a province"}
如何让PHP格式化我的简单数组以包含JSON中的属性?
答案 0 :(得分:4)
只需创建一个新数组:
$data = array();
foreach($array as $key => $value) {
$data[] = array('pk' => $key, 'name' => $value);
}
$json = json_encode($data);