[英]php how to grouping by id
I'm very new in PHP. 我是PHP的新手。 I'm doing with the array data structure. 我正在处理数组数据结构。 Currently, I got two result which is the same ID but different details. 目前,我得到两个结果,它们是相同的ID,但细节不同。 I need to combine the details based on the ID. 我需要根据ID合并详细信息。
This is my array result 这是我的数组结果
array:2 [
0 => array:13 [
"id" => "1"
"date" => "01-02-2019"
"order" => array:1 [
0 => array:2 [
"code" => "F001"
"name" => "fish"
]
]
]
1 => array:13 [
"id" => "1"
"date" => "01-02-2019"
"order" => array:1 [
0 => array:2 [
"code" => "F002"
"name" => "chicken"
]
]
]
]
This is my expected result 这是我的预期结果
array:1 [
0 => array:13 [
"id" => "1"
"date" => "01-02-2019"
"order" => array:2 [
0 => array:2 [
"code" => "F001"
"name" => "fish"
]
1 => array:2 [
"code" => "F002"
"name" => "chicken"
]
]
]
]
I'm trying to insert the order array if there have the same id 我试图插入订单数组,如果有相同的ID
This is my code 这是我的代码
public function order($value)
{
$group_id = [];
$groupItem = [];
foreach ($value as $item) {
$item['date'] = date('Y-m-d',strtotime($item['date']));
$groupItem = $item['order'][] = [
'id' => $item['id'],
'name' => $item['name'],
];
$group_id[$item['id']][]= $groupItem;
}
}
Result 结果
array:1 [
"1" => array:1 [
0 => array:2 [
"code" => "F001"
"name" => "fish"
]
1 => array:2 [
"code" => "F002"
"name" => "chicken"
]
]
]
As you can see, I grouped the order
but the date and id were missing. 如您所见,我将order
分组,但是缺少日期和ID。
Assign the proper data. 分配适当的数据。 Try - 尝试-
foreach ($value as $item) {
$date = date('Y-m-d',strtotime($item['date']));
$id = $item['id'];
$group_id[$id]['id'] = $id;
$group_id[$id]['date'] = $date;
$group_id[$id]['order'][] = [
'id' => $item['id'],
'name' => $item['name'],
];
}
I would write something like this, if you need to account for multiple IDs: 如果您需要考虑多个ID,我会写这样的内容:
$result = array_reduce( $input, function ( $result, $item ) {
$id = $item['id'];
if ( ! isset( $result[ $id ] ) ) { // We don't have an item yet.
$result[ $id ] = $item;
} else { // We have an item and need to add orders to it.
$result[ $id ]['order'] = array_merge( $result[ $id ]['order'], $item['order'] );
}
return $result;
}, [] );
Here is a working order function: 这是一个工作指令功能:
function order($input) {
$output = array();
foreach($input as $item) {
if (!isset($output[$item['id']])) {
$output[$item['id']] = array(
"id" => $item["id"],
"date" => $item["date"],
"order" => array()
);
}
$output[$item['id']]['order'][] = $item['order'];
}
return array_values($output);
}
INPUT: 输入:
array(
array(
"id" => "1",
"date" => "01-02-2019",
"order" => array(
array(
"code" => "F001",
"name" => "fish"
)
)
),
array(
"id" => "1",
"date" => "01-02-2019",
"order" => array(
array(
"code" => "F002",
"name" => "chicken"
)
)
)
);
OUTPUT: 输出:
array(
array(
"id"=> "1",
"date"=> "01-02-2019",
"order"=> array(
array(
array(
"code"=> "F001",
"name"=> "fish"
)
),
array(
array(
"code"=> "F002",
"name"=> "chicken"
)
)
)
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.