1

I have an array and there is a userID key. What I want is to make the userid as parent key. Thee current variable I have is below:

$data = array(
    [0]=>array(
        [userID] => 90
        [dateLogin] =>  23:35:13
        [type] => 28
    ), 

    [1]=>array(
        [userID] => 90
        [dateLogin] =>  23:35:10
        [type] => 29
    ), 
    [2]=>array(
        [userID] => 91
        [dateLogin] =>  23:35:13
        [type] => 25
    ), 

    [3]=>array(
        [userID] => 91
        [dateLogin] =>  23:35:10
        [type] => 23
    )
)

Now I want to achieve the output like below as you can see the userID which 90 and 91 become the key and it has array inside:

$data = array(
    [90]=> array(
        [0] => array(
            [userID] => 90
            [dateLogin] =>  23:35:13
            [type] => 28
         ),
        [1]=>array(
            [userID] => 90
            [dateLogin] =>  23:35:10
            [type] => 29
         ),
      ), 
      [91]=> array(
         [0]=>array(
            [userID] => 91
            [dateLogin] =>  23:35:13
            [type] => 25
          ),
        [1]=>array(
           [userID] => 91
           [dateLogin] =>  23:35:10
           [type] => 23
        )
     ), 
  )

what I've done so far is:

   foreach ($data as $key => $value) {
       $data[$value['userID']] = array(); 
          foreach ($value as $k => $v) {
            if($v == $value['userID']){
                $data[$value['userID']][] = $value; 
            }
        }
    }

I can now make the userID as key but the array inside of it is wrong. What am I wrong missing.? Please help. Thanks

Zero
  • 375
  • 1
  • 5
  • 9

1 Answers1

0

No need for that inner foreach, just one should suffice:

$new_data = array();
foreach($data as $value) {
    $new_data[$value['userID']][] = $value;
           // ^ userID as key   ^ another dimension
}
Kevin
  • 41,694
  • 12
  • 53
  • 70