我将从我的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
)
)
我想把它带出来json_encode($response);
所需的格式为:
$out = [
'2021-08-10' => [ 'A0304' =>[48=>1000],
'A0301' =>[40=>1002,4=>1000]
],
'2021-08-11' => [ 'A0301' =>[30=>1000,4=>1000] ],
]
通过使用这段代码,我没有得到完整的结果。我该怎么做?
$out = [];
foreach ($results as $result)
{
$out[$result['date']] = $result['date'];
if ( !isset($out[$result['date']]) ) {
$out['date'][] = $result['date'];
}
}
$response['data'] = $out;
这里是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) } }
这里是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, ), )
要实现您所要求的结果,使用以下循环
$out = [];
foreach ($results as $result) {
$out[$result['date']][$result['desk']][$result['slot']] = $result['userId'];
}