我有以下多维数组
if($this->conn->row_count($sql)==true){
while($row=$statement->fetch()){
$problems[]=[
'order_id'=>$row['order_id'],
'details'=>['remark'=>$row['remark'],'date'=>$row['date']]
];
}
return $problems;
}
然后我打印出来
echo '<pre>',print_r($problems),'</pre>';
结果
Array
(
[0] => Array
(
[order_id] => 4683
[details] => Array
(
[remark] => happy
[date] => 2018-06-09---10:16:41am
)
)
[1] => Array
(
[order_id] => 4683
[details] => Array
(
[remark] => unhappy
[date] => 2018-06-10---03:29:00am
)
)
[2] => Array
(
[order_id] => 4440
[details] => Array
(
[remark] => very unhappy
[date] => 2018-06-10---03:34:00am
)
)
)
我正在尝试将它们分组到一个新的多维数组中,如果相同的order_id和连接细节。 order_id可能有2个以上,因为此order_id可能会有更多评论 *,就像下面的
一样Array
(
[0] => Array
(
[order_id] => 4683
[details] => Array
(
[remark] => happy
[date] => 2018-06-09---10:16:41am
),
(
[remark] => unhappy
[date] => 2018-06-10---03:29:00am
)
)
[1] => Array
(
[order_id] => 4440
[details] => Array
(
[remark] => very unhappy
[date] => 2018-06-10---03:34:00am
)
)
)
要获得更清晰的图片,请查看截图
知道如何像输出那样创建一个新数组吗?
答案 0 :(得分:1)
您可以通过关联数组对其进行分组。您可以使用array_values
将关联数组转换为简单数组。
$problems = [];
if($this->conn->row_count($sql)==true){
while($row=$statement->fetch()){
if ( !isset( $problems[ $row['order_id'] ] ) ) {
$problems[ $row['order_id'] ] = [
'order_id' => $row['order_id'],
'details' => []
];
}
$problems[ $row['order_id'] ]['details'][] = ['remark'=>$row['remark'],'date'=>$row['date']];
}
return array_values( $problems );
}