我的桌子上有10条记录。
id value
------------
1 record-1
2 record-2
3 record-3
4 record-4
5 record-5
6 record-6
7 record-7
8 record-8
9 record-9
10 record-10
我想创建这个json:
[
{
"1":"record-1",
"2":"record-2"
},
{
"3":"record-3",
"4":"record-4"
},
{
"5":"record-5",
"6":"record-6"
},
{
"7":"record-7",
"8":"record-8"
},
{
"9":"record-9",
"10":"record-10"
}
]
假设所有记录都在$records
变量中。
答案 0 :(得分:1)
我们需要在这里使用array_chunk()功能。
试试这个:
$result = array_chunk($records, 2, true);
echo json_encode($result);
输出:
[{"1":"record-1","2":"record-2"},{"3":"record-3","4":"record-4"},{"5":"record-5","6":"record-6"},{"7":"record-7","8":"record-8"},{"9":"record-9","10":"record-10"}]
答案 1 :(得分:0)
你可以试试这个:
$crecords = array_chunk($records , 2, true);
返回两个记录作为数组元素。现在使用for循环生成json:
foreach($crecords as $jsons){
//print_r($jsons)...you got the json object by json_encode..
}
答案 2 :(得分:0)
你可以试试这个:
<?php
$array = array(
'record-1',
'record-2',
'record-3',
'record-4',
'record-5',
'record-6',
'record-7',
'record-8',
'record-9',
'record-10',
);
array_unshift($array, "phoney"); // changing array keys from starting 0 to 1 // dummy value
unset($array[0]); // unsetting or removing value from array key 0
$final_arr = array_chunk($array, 2,true);
$json = array();
foreach ($final_arr as $key => $value)
{
$json[$key] = $value;
}
echo json_encode($json);
?>
这应该为您提供所需的json输出。
输出:
[
{
"1": "record-1",
"2": "record-2"
},
{
"3": "record-3",
"4": "record-4"
},
{
"5": "record-5",
"6": "record-6"
},
{
"7": "record-7",
"8": "record-8"
},
{
"9": "record-9",
"10": "record-10"
}
]