PHP How to group json object

后端 未结 1 537
青春惊慌失措
青春惊慌失措 2021-01-27 14:07

i want to ask about json object

i have json object like this:

{\"ID\":\"HC\",\"ID_NAME\":\"Human Capital\",\"TASK_ID\":\"HC01\",\"TASK_NAME\":\"Human ser         


        
相关标签:
1条回答
  • 2021-01-27 14:20

    We decode the JSON, loop through the objects, add unique IDs to a new array, create a placeholder array for ITEMS, and append the TASK to this ITEMS. After this is all done, we can re-encode the data and return.

    Code:

    // 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);
    

    Output:

    Example output

    Documentation:

    • json_decode() and json_encode()
    • stdClass
    • array_key_exists
    • array_values
    0 讨论(0)
提交回复
热议问题