PHP如何分组json对象

时间:2014-04-17 03:05:43

标签: php arrays json

我想问一下json对象

我有这样的json对象:

{"ID":"HC","ID_NAME":"Human Capital","TASK_ID":"HC01","TASK_NAME":"Human service 1"}
{"ID":"MM","ID_NAME":"Management","TASK_ID":"MM01","TASK_NAME":"Management 1"}
{"ID":"HC","ID_NAME":"Human Capital","TASK_ID":"HC02","TASK_NAME":"Human service 2"}
{"ID":"HC","ID_NAME":"Human Capital","TASK_ID":"HC03","TASK_NAME":"Human service 3"}
{"ID":"QC","ID_NAME":"Quality Control","TASK_ID":"QC01","TASK_NAME":"Quality Control 1"}
{"ID":"HC","ID_NAME":"Human Capital","TASK_ID":"HC04","TASK_NAME":"Human service 4"}

我想将具有相同id,id_name的json对象分组。例如像这样

{"ID":"HC","ID_NAME":"Human Capital","items": [
     {"TASK_ID":"HC01","TASK_NAME":"Human service 1"},
     {"TASK_ID":"HC02","TASK_NAME":"Human service 2"},
     {"TASK_ID":"HC03","TASK_NAME":"Human service 3"},
     {"TASK_ID":"HC04","TASK_NAME":"Human service 4"}
   ]
},
{"ID":"MM","ID_NAME":"Management","items": [
     {"TASK_ID":"MM01","TASK_NAME":"Managemen 1"}
   ]
},
{"ID":"QC","ID_NAME":"Quality Control","items": [
     {"TASK_ID":"QC01","TASK_NAME":"Quality Control 1"}
   ]
},

请帮助我学习。

1 个答案:

答案 0 :(得分:2)

我们解码JSON,遍历对象,将唯一ID添加到新数组,为ITEMS创建占位符数组,并将TASK附加到此ITEMS }}。完成所有操作后,我们可以重新编码数据并返回。

<强>代码:

// Your JSON array of objects
$json = <<<JSON
[
  {"ID":"HC","ID_NAME":"Human Capital","TASK_ID":"HC01","TASK_NAME":"Human service 1"},
  {"ID":"MM","ID_NAME":"Management","TASK_ID":"MM01","TASK_NAME":"Management 1"},
  {"ID":"HC","ID_NAME":"Human Capital","TASK_ID":"HC02","TASK_NAME":"Human service 2"},
  {"ID":"HC","ID_NAME":"Human Capital","TASK_ID":"HC03","TASK_NAME":"Human service 3"},
  {"ID":"QC","ID_NAME":"Quality Control","TASK_ID":"QC01","TASK_NAME":"Quality Control     1"},
  {"ID":"HC","ID_NAME":"Human Capital","TASK_ID":"HC04","TASK_NAME":"Human service 4"}
]
JSON;

// Decode your JSON and create a placeholder array
$objects = json_decode($json);
$grouped = array();

// Loop JSON objects
foreach($objects as $object) {
    if(!array_key_exists($object->ID, $grouped)) { // a new ID...
         $newObject = new stdClass();

         // Copy the ID/ID_NAME, and create an ITEMS placeholder
         $newObject->ID = $object->ID;
         $newObject->ID_NAME = $object->ID_NAME;
         $newObject->ITEMS = array();

         // Save this new object
         $grouped[$object->ID] = $newObject;
    }

    $taskObject = new stdClass();

    // Copy the TASK/TASK_NAME
    $taskObject->TASK_ID = $object->TASK_ID;
    $taskObject->TASK_NAME = $object->TASK_NAME;

    // Append this new task to the ITEMS array
    $grouped[$object->ID]->ITEMS[] = $taskObject;
}

// We use array_values() to remove the keys used to identify similar objects
// And then re-encode this data :)
$grouped = array_values($grouped);
$json = json_encode($grouped);

<强>输出:

Example output

<强>文档