PHP How to group json object

后端 未结 1 554
青春惊慌失措
青春惊慌失措 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 = <<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)
提交回复
热议问题