我已经将一个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
对这两个数组进行分组。
答案 0 :(得分:2)
我在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;
}
这里正在工作example