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

大豆

我已经将一个csv文件转换为数组,并使用一些键将数组数据分组。我定义了一个groupBy函数来处理数组数据。但是,我遇到此错误,不确定哪一部分出错。

代码: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

卡米尔(KamilKiełczewski)

我重写您的代码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;
}

这是工作示例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

PHP数组上的非法字符串偏移警告

PHP 7.1.6的非法字符串偏移

非法字符串偏移量'名称'laravel PHP

非法的字符串偏移量'name'php-多个数组成1个数组

尝试在数组中打印值时出现非法字符串偏移

Laravel在尝试循环JSON API响应时给出了非法的字符串偏移量

警告非法字符串偏移PHP

非法字符串偏移“名称”错误

按数组分组

Laravel-非法字符串偏移量

Laravel:第342行上的非法字符串偏移“文件”,文件Illuminate / Mail / Mailable.php

Laravel Voyager新用户登录中的非法字符串偏移'locale'错误

多维数组中的非法字符串偏移

数组显示但子数组显示“非法字符串偏移”错误-PHP

具有字符串数组的受保护属性返回非法的字符串偏移量“选项”

从数组中获取值时出现非法字符串偏移警告

PHP-数组-非法的字符串偏移量

Laravel中的非法字符串偏移

echo会话数组值-警告非法的字符串偏移量

警告:字符串偏移量非法(在数组上)

非法字符串偏移'slug' PDO

如何解决打印数组值时出现非法字符串偏移错误?

即使我已经在控制器中解码了数组,字符串偏移还是非法?

多维数组 - 非法字符串偏移

当数组位于 std 对象中时,如何从数组中访问数据?错误:非法字符串偏移“id”

处理 json 解码数组时出现非法字符串偏移

在Javascript中按字偏移拆分字符串

非法字符串偏移'id' laravel 7

如何解決laravel中的非法字符串偏移問題