[英]Merge the rows of two arrays (appending row data from one array to a row in another array)
I have two arrays populated from CodeIgniter query result sets (from calls of result_array()
) and I need to merge the rows from the two arrays respectively/synchronously.我有两个 arrays 从 CodeIgniter 查询结果集(来自
result_array()
的调用)填充,我需要分别/同步合并来自两个 arrays 的行。
$array1 = [
['name' => 'John', 'course' => 'BSIT'],
['name' => 'Jane', 'course' => 'BSHRM'],
];
$array2 = [
['balance' => '1000', 'date' => '2013-05-01'],
['balance' => '2000', 'date' => '2013-05-07'],
];
How can I append the elements [balance], [date]
from $array2
to $array1
so that the result looks like this:我怎样才能 append 元素
[balance], [date]
从$array2
到$array1
以便结果如下所示:
[
[
'name' => 'John',
'course' => 'BSIT',
'balance' => '1000',
'date' => '2013-05-01'
],
[
'name' => 'Jane',
'course' => 'BSHRM',
'balance' => '2000',
'date' => '2013-05-07'
]
]
I have tried:我努力了:
for($i = 0; $i<count($array1); $i++)
{
array_merge($array1[$i], $array2[$i]);
}
but I get an error that arguments are not array
even if I do it like this:但我得到一个错误,即
arguments are not array
,即使我这样做:
for($i = 0; $i<count($array1); $i++)
{
array_merge(array($array1[$i]), array($array2[$i]));
}
Try setting the array_merge equal to something: 尝试将array_merge设置为等于:
for($i = 0; $i<count($array1); $i++)
{
$array1[$i] = array_merge($array1[$i], $array2[$i]);
}
$merged_array = array_map(function($a, $b) {
return array_merge($a, $b);
}, $array1, $array2));
尝试使用array_merge_recursive()函数
There is a simpler way to merge the rows of two or more arrays.有一种更简单的方法可以合并两个或多个 arrays 的行。 Call
array_map()
with a callback of array_merge()
and then list the arrays as final function parameters.使用
array_merge()
回调调用array_map()
,然后将 arrays 作为最终 function 参数列出。 array_map()
will synchronously isolate one row at a time from the input arrays so that array_merge()
can combine the two rows into one. array_map()
将一次从输入 arrays 中同步隔离一行,以便array_merge()
可以将两行合并为一。
var_export(
array_map('array_merge', $array1, $array2)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.