对两个数组进行分组
我已经将CSV文件转换为数组,并将数组数据分组为一些键。我定义了一个组函数来处理数组数据。但是,我面临此错误,不确定哪个部分出错。
代码:Groupby功能
public function group($key, $item) {
$result = array();
foreach($item as $val) {
$result[$val[$key]][] = $val; <--error $key
}
return $result;
}
数据转换功能。
public function saveNewSale()
{
foreach (array_chunk($items, $chunk_size) as $chunk) {
$cleaned_items = [];
foreach ($chunk as $item) {
//Data Transformation
//call groupby function
$byGroup = $this->group('ref_num', $item);
array_push($cleaned_items, $item);
}
这是我的数组
array:2 [
0 => array:13 [
"ref_num" => "INV699"
"payment_term" => array:2 [
"id" => 1
"name" => "Cash"
]
"items" => array:1 [
0 => array:8 [
"code" => "3MVR0003"
"description" => "3M Vinyl
"tax_value" => 0.06
"qty" => 1
"unit" => 1
"price" => 10
"total" => 212
"total_tax" => 12
]
]
"terms" => array:1 [
0 => array:2 [
"date" => "2019-02-20"
"amount" => 200
]
]
]
1 => array:13 [
"ref_num" => "INV699"
"payment_term" => array:2 [
"id" => 1
"name" => "Cash"
]
"items" => array:1 [
0 => array:8 [
"code" => "sony"
"description" => "3xperia"
"tax_value" => 0.06
"qty" => 1
"unit" => 1
"price" => 10
"total" => 212
"total_tax" => 12
]
]
"terms" => array:1 [
0 => array:2 [
"date" => "2019-02-20"
"amount" => 200
]
]
]
]
我需要基于ref_num
。
我在saveNewSale
中重写您的代码,然后删除group
功能
public function saveNewSale($items)
{
$groupedArray = [];
foreach (array_chunk($items, 2) as $chunk)
{
foreach($chunk as $entry) {
$groupedArray[$entry['ref_num']][]= $entry;
}
}
return $groupedArray;
}
这是有效的示例