我在so和google中进行搜索,但是找不到解决我问题的任何方法。有类似问题的答案。 而且,如果我在json中有一百多个对象,那么foreach可能会很慢。
感谢您的咨询
$list = json_decode($string);
$grouped = array();
foreach($list as $object) {
if(!array_key_exists($object->id, $grouped)) {
$newObject = new stdClass();
$newObject->id = $object->id;
$newObject->tip = $object->tip;
$newObject->kar = array();
$grouped[$object->id] = $newObject;
}
$taskObject = new stdClass();
$taskObject->tur = $object->kar->tur;
$taskObject->tid = $object->kar->tid;
$taskObject->pric = $object->kar->pric;
$grouped[$object->id]->kar[] = $taskObject;
}
$grouped = array_values($grouped);
$json = json_encode($grouped);
var_dump($json);
我的json ..
{
"roms": [{
"tip": "bane",
"id": "327034409",
"kar": [{
"tur": "ray",
"tid": "989530150",
"pric": "3.25"
}]
},
{
"tip": "bane",
"id": "327034409",
"kar": [{
"tur": "kay",
"tid": "989530151",
"pric": "1.67"
}]
},
{
"tip": "bane",
"id": "327034409",
"kar": [{
"tur": "tay",
"tid": "989530152",
"pric": "5"
}]
},
{
"tip": "yane",
"id": "327034410",
"kar": [{
"tur": "kay",
"tid": "989530153",
"pric": "14"
}]
},
{
"tip": "yane",
"id": 327034410,
"kar": [{
"tur": "tay",
"tid": "989530154",
"pric": "3.75"
}]
},
{
"tip": "yane",
"id": 327034410,
"kar": [{
"tur": "lay",
"tid": "989530155",
"pric": "1.3"
}]
},
{
"tip": "rula",
"id": "327162383",
"kar": [{
"tur": "ray",
"tid": "989855757",
"pric": "3"
}]
},
{
"tip": "rula",
"id": "327162383",
"kar": [{
"tur": "rok",
"tid": "989855758",
"pric": "1.83"
}]
},
{
"tip": "rula",
"id": 327162383,
"kar": [{
"tur": "lok",
"tid": 989855759,
"pric": "4.4"
}]
}
]
}
我想以相同的tur / id将表单对象分组。 并且我想对具有相同id,tur / tidname的json对象进行分组。像这样 我要..
{
"roms": [{
"tip": "bane",
"id": "327034409",
"kar": [{
"tur": "ray",
"tid": "989530150",
"pric": "3.25"
}, {
"tur": "kay",
"tid": "989530151",
"pric": "1.67"
}, {
"tur": "tay",
"tid": "989530152",
"pric": "5"
}]
},
{
"tip": "yane",
"id": "327034410",
"kar": [{
"tur": "kay",
"tid": "989530153",
"pric": "14"
}, {
"tur": "tay",
"tid": "989530154",
"pric": "3.75"
}, {
"tur": "lay",
"tid": "989530155",
"pric": "1.3"
}]
},
{
"tip": "rula",
"id": "327162383",
"kar": [{
"tur": "ray",
"tid": "989855757",
"pric": "3"
}, {
"tur": "rok",
"tid": "989855758",
"pric": "1.83"
}, {
"tur": "lok",
"tid": "989855759",
"pric": "4.4"
}]
}
]
}
答案 0 :(得分:0)
我认为这是正确的解决方案。
我更改了一些部分,例如遍历rom($ list-> roms)而不是遍历列表。 tur,tid和pric并不是直系子代,但它们是数组的第一个元素。
$list = json_decode($string);
$grouped = array();
foreach ($list->roms as $object) {
if (!array_key_exists($object->id, $grouped)) {
$newObject = new stdClass();
$newObject->id = $object->id;
$newObject->tip = $object->tip;
$newObject->kar = array();
$grouped[$object->id] = $newObject;
}
$taskObject = new stdClass();
$taskObject->tur = $object->kar[0]->tur;
$taskObject->tid = $object->kar[0]->tid;
$taskObject->pric = $object->kar[0]->pric;
$grouped[$object->id]->kar[] = $taskObject;
}
$grouped = ['roms' => array_values($grouped)];
$json = json_encode($grouped);
var_dump($json);