我有一个像这样的基本数组:
[
{
"id": 4,
"name": "Ray"
},
{
"id": 5,
"name": "Anthony"
}
]
我需要返回一系列这些数组作为单个json消息的一部分。根据{{3}},我似乎无法做到正确。例如,我有一群人。每个组都是一组人,每个组应该是父数组的不同元素。应该如何格式化?
澄清:
group1: ray, anthony
group2: john, mike
group3: ed, dan
依旧......
答案 0 :(得分:2)
只需将它们分成两组,从PHP创建结构,然后像往常一样使用json_encode()
。例如:
$groups = array(
'group1' => array(
array('id' => 4, 'name' => 'Ray'),
array('id' => 5, 'name' => 'Anthony'),
),
'group2' => array(
array('id' => 6, 'name' => 'john'),
array('id' => 7, 'name' => 'mike'),
),
'group3' => array(
array('id' => 8, 'name' => 'ed'),
array('id' => 9, 'name' => 'dan'),
),
);
echo '<pre>';
print_r(json_encode($groups, JSON_PRETTY_PRINT));
应该产生类似的东西:
{
"group1": [
{
"id": 4,
"name": "Ray"
},
{
"id": 5,
"name": "Anthony"
}
],
"group2": [
{
"id": 6,
"name": "john"
},
{
"id": 7,
"name": "mike"
}
],
"group3": [
{
"id": 8,
"name": "ed"
},
{
"id": 9,
"name": "dan"
}
]
}
答案 1 :(得分:0)
我猜这有效:
{
"g1": [
{
"id": 4,
"name": "Ray"
},
{
"id": 5,
"name": "Anthony"
}
],
"g2": [
{
"id": 4,
"name": "Mike"
},
{
"id": 5,
"name": "John"
}
]
}
答案 2 :(得分:0)
var groups = [
"G1" : {
"11" : {
"id" : 11,
"name" : "jhon"
},
"3" : {
"id" : 3,
"name" : "erik"
}
},
"G2" : {
"8" : {
"id" : 8,
"name" : "jean"
},
"4" : {
"id" : 4,
"name" : "jim"
}
}
]
在任何组内部,任何对象的键都是该人的ID(字符串格式),以便于访问其数据。
离。
group.G2[8]; // return jean object
PHP格式:
$g = array(
'G1' => array(
'11' => array('id' => 11, 'name' => 'jhon'),
'3' =>array('id' => 3, 'name' => 'erik')
),
'G2' => array(
'8' => array('id' => 8, 'name' => 'jean'),
'4' => array('id' => 4, 'name' => 'jim')
)
);