php - DB result to json

I will get the following array from my DB:

Array
(
    [0] => Array
        (
            [userId] => 1000
            [desk] => A0304
            [date] => 2021-08-10
            [slot] => 48
        )

    [1] => Array
        (
            [userId] => 1002
            [desk] => A0301
            [date] => 2021-08-10
            [slot] => 40
        )

    [2] => Array
        (
            [userId] => 1000
            [desk] => A0301
            [date] => 2021-08-10
            [slot] => 4
        )



    [3] => Array
        (
            [userId] => 1000
            [desk] => A0301
            [date] => 2021-08-11
            [slot] => 30
        )

    [4] => Array
        (
            [userId] => 1000
            [desk] => A0301
            [date] => 2021-08-11
            [slot] => 4
        )

)

I would like to bring it to out by json_encode($response);

The desired format shout be:

$out = [
 '2021-08-10' => [ 'A0304' =>[48=>1000],
                   'A0301' =>[40=>1002,4=>1000]
                 ],
 '2021-08-11' => [ 'A0301' =>[30=>1000,4=>1000] ],
]

By using this code I do not get the complete result. What I have to do?

 $out = [];

 foreach ($results as $result)
  {
      $out[$result['date']] = $result['date'];
      if ( !isset($out[$result['date']]) ) {
         $out['date'][] = $result['date'];
      }

  }

  $response['data'] = $out;

here is the var_dump:

array(5) { [0]=> array(4) { ["userId"]=> int(1000) ["desk"]=> string(5) "A0304" ["date"]=> string(10) "2021-08-10" ["slot"]=> int(48) } [1]=> array(4) { ["userId"]=> int(1000) ["desk"]=> string(5) "A0301" ["date"]=> string(10) "2021-08-10" ["slot"]=> int(40) } [2]=> array(4) { ["userId"]=> int(1000) ["desk"]=> string(5) "A0301" ["date"]=> string(10) "2021-08-10" ["slot"]=> int(4) } [3]=> array(4) { ["userId"]=> int(1000) ["desk"]=> string(5) "A0301" ["date"]=> string(10) "2021-08-10" ["slot"]=> int(30) } [4]=> array(4) { ["userId"]=> int(1000) ["desk"]=> string(5) "A0301" ["date"]=> string(10) "2021-08-11" ["slot"]=> int(4) } } 

here is the var_export:

array ( 0 => array ( 'userId' => 1000, 'desk' => 'A0304', 'date' => '2021-08-10', 'slot' => 48, ), 1 => array ( 'userId' => 1000, 'desk' => 'A0301', 'date' => '2021-08-10', 'slot' => 40, ), 2 => array ( 'userId' => 1000, 'desk' => 'A0301', 'date' => '2021-08-10', 'slot' => 4, ), 3 => array ( 'userId' => 1000, 'desk' => 'A0301', 'date' => '2021-08-10', 'slot' => 30, ), 4 => array ( 'userId' => 1000, 'desk' => 'A0301', 'date' => '2021-08-11', 'slot' => 4, ), )

Answer

Solution:

To implement the result like you requested, use the following loop

$out = [];
foreach ($results as $result) {
    $out[$result['date']][$result['desk']][$result['slot']] = $result['userId'];

}

Source