Home > Mobile >  How to group the nested array based on id?
How to group the nested array based on id?

Time:06-19

Maybe the question title didnot clear enough, Basically i have an array of associative array that returned from database like this:

persons = [
           [id=>1, name=>adam, hobbyId=>x, hobbyName=> swim],
           [id=>2, name=>brian, hobbyId=>y, hobbyName=> read],
           [id=>1, name=>adam, hobbyId=>z, hobbyName=> sing]
          ]

I want to convert it to new style like JSON object, something like this:

new_persons = [
               [id=>1, name=>adam, hobbies => [[hobbyId=>x, hobbyName=> swim],[hobbyId=>z, 
                hobbyName=> sing]],
               [id=>2, name=>brian, hobbies => [[hobbyId=>y, hobbyName=>read]]
              ]

what i have tried:

$new_persons = array();
        if (count($persons) > 0) {
            foreach ($persons as $item) {
                $detail = array(
                    'id' => $item['id'],
                    'name' => $item['name'],
                    'hobbies' => [['hobbyId'=>$item['hobbyId'],'hobbyName'=>$item['hobbyName']]]
                );
                if (in_array($item['id'], $newArray)) {
                    array_push($newArray['hobbies'], ['hobbyId'=>$item['hobbyId'],'hobbyName'=>$item['hobbyName']]);
                } else {
                    array_push($newArray, $detail);
                }
            }
        }

But it doesnt meet what i need, what have i do wrong? thank you

CodePudding user response:

$t2 = [];
foreach ($t as $item) {
    if (!isset($t2[$item['id']])) {
        $t2[$item['id']] = [
            'id'   => $item['id'],
            'name' => $item['name'],
        ];
    }
    $t2[$item['id']]['hobbies'][] = [
            'hobbyId'   => $item['hobbyId'],
            'hobbyName' => $item['hobbyName'],
    ];
}
  • Related