我有一个数组“ pollAnswers”,其中显示:
Array
(
[0] => Sachin
[1] => Dhoni
)
在PHP中,我希望它显示为:
"pollAnswers":[
{"pollAnswersID":0, "pollAnswer":"Sachin"},
{"pollAnswersID":1, "pollAnswer":"Dhoni"}
]
在JSON输出中。
我尝试使用array_fill_keys和array_flip,但这不是解决方案。似乎我需要拆分array_keys和array_values,然后进行一些串联以获取此信息,但是我被困在这里!
最佳答案
在线检查link
试试这个
$arr = array("Sachin", "Dhoni");
$sub_arr = array();
$final = array();
foreach($arr as $key => $val){
$sub_arr['pollAnswersId'] = $key;
$sub_arr['pollAnswer'] = $val;
$sub_final[] = $sub_arr;
}
$final['pollAnswers'] = $sub_final;
echo json_encode($final);
结果
{"pollAnswers":[
{"pollAnswersId":0,"pollAnswer":"Sachin"},
{"pollAnswersId":1,"pollAnswer":"Dhoni"}
]}