我通过array_merge()有两个看起来像这样的数组:
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数组中,有人可以向我展示合并这些数组的正确方法吗?
答案 0 :(得分:0)
使用array_merge和array_key_exists函数以及一些基本的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;
}
}