【发布时间】:2017-04-11 23:46:34
【问题描述】:
我在 PHP 中有以下示例代码:
$data = array(
'hello',
'world',
'hi'
);
$ret = array();
$ret['test'] = array();
$ret['testing'] = array();
foreach($data as $index => $value){
if($index < 1){
$ret['test'][$index]['val'] = $value;
$ret['test'][$index]['me'] = 'index < 1';
}
else {
$ret['testing'][$index]['val'] = $value;
$ret['testing'][$index]['me'] = 'index >= 1';
}
}
echo json_encode($ret);
我希望这是 JSON 输出:
[{
"test":[
{
"val": "hello",
"me": "index < 1"
}
],
"testing":[
{
"val": "world",
"me": "index >= 1"
},
{
"val": "hi",
"me": "index >= 1"
}
]
}]
然而,最终发生的事情是我得到了以下结果:
[{
"test":[
{
"val": "hello",
"me": "index < 1"
}
],
"testing":{
"1":{
"val": "world",
"me": "index >= 1"
},
"2":{
"val": "hi",
"me": "index >= 1"
}
}
}]
"1" 和 "2" 键虽然是 int 并且尽管在使用相同的计数器变量时正确呈现了 test,但仍会出现。有没有办法确保testing 成为 JSON 对象数组?
【问题讨论】: