Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP按相同索引合并数组_Php_Laravel - Fatal编程技术网

PHP按相同索引合并数组

PHP按相同索引合并数组,php,laravel,Php,Laravel,我有两个按数组合并的数组,如下所示: Array( [1] => Array( [date] => 2018-09-25 [size_one] => 'XL' [name_one] => 'Shoes' ) [2] => Array( [d

我有两个按数组合并的数组,如下所示:

 Array(
            [1] => Array(
                  [date] => 2018-09-25
                  [size_one] => 'XL'
                  [name_one] => 'Shoes'
                )
            [2] => Array(
                    [date] => 2018-09-25
                    [size_two] => 'L'
                    [name_two] => 'Shirt'
                )
            [3] => Array(
                    [date] => 2018-09-26
                    [size_two] => 'L'
                    [name_two] => 'Shirt'
                )
            )
如果是相同的日期值,我需要如下结果:

Array(
                [1] => Array(
                      [date] => 2018-09-25
                      [size_one] => 'XL'
                      [name_one] => 'Shoes'
                      [size_two] => 'L'
                      [name_two] => 'Shirt'
                    )
                [2] => Array(
                        [date] => 2018-09-26
                        [size_two] => 'L'
                        [name_two] => 'Shirt'
                    )
                )
要将这些数组放入laravel的数组中,有人能告诉我合并这些数组的正确方法吗?

使用and函数,以及一些基本的foreach循环和条件,您可以尝试代码注释中解释的以下步骤:

// $input is your input array

// initialize output array
$output = array();

// loop over the input
foreach ($input as $key => $value) {

    // check if the date key is already set in the output or not
    if ( array_key_exists($value['date'], $output) ) {

        // this is duplicate based on date - merge into output
        $output[$value['date']] = array_merge($output[$value['date']], 
                                              $value);
    } else {

        // new entry for date
        $output[$value['date']] = $value;
    }
}

那就是工作。。谢谢。@gilangtaufik很乐意帮助您:您可以使用laravel collection。首先需要按日期分组,然后合并每个组并删除键$结果=收集$input->groupBy'date'->mapfunction$item{returnarray\u merge…$item->toArray;}->值;