Laravel按数组分组-非法字符串偏移

时间:2019-02-20 07:47:24

标签: php arrays laravel-4

我已经将一个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对这两个数组进行分组。

1 个答案:

答案 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