[英]Merge two array elements in new one
I have two array. 我有两个数组。
$a = ['0' => 1, '1' => 2, '2' => 3]
$b = ['0' => 4, '1' => 5, '2' => 6]
i want to create new array like this 我想像这样创建新的数组
$c = [['a' => 1, 'b' => '4'], ['a' => '2', 'b' => '5']]
I have tried these functions array_merge
, array_merge_recursive
but did not get positive results 我已经尝试过这些函数
array_merge
, array_merge_recursive
但没有得到积极的结果
$data = array_merge_recursive(array_values($urls), array_values($id));
You have to apply array_map() with custom function: 您必须通过自定义函数应用array_map() :
$newArray = array_map('combine',array_map(null, $a, $b));
function combine($n){
return array_combine(array('a','b'),$n);
}
print_r($newArray);
Output:- https://3v4l.org/okML7 输出: -https : //3v4l.org/okML7
Try this one 试试这个
$c = array_merge($a,$b)
$d[] = array_reduce($d, 'array_merge', []);
It will merge the two array and reduce and remerge it. 它将合并两个数组,并减少和重新合并它。
You can use foreach
to approach this 您可以使用
foreach
来解决这个问题
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$res = [];
$i = 0;
$total = 2;
foreach($a as $k => $v){
$res[$i]['a'] = $v;
$res[$i]['b'] = $b[$k];
$i++;
if($i == $total) break;
}
The idea is to have an array $ab = ['a','b']
and a array from your both arrays like this $merged_array = [[1,4],[2,5],[3,6]]
. 这个想法是让一个数组
$ab = ['a','b']
和两个数组中的一个数组,像这样$merged_array = [[1,4],[2,5],[3,6]]
。
Now we can combine array $ab
with each element of $merged_array
and that will be the result we need. 现在我们可以将数组
$ab
与$merged_array
每个元素组合在一起,这将是我们需要的结果。
$first = ['0' => 1, '1' => 2, '2' => 3];
$second = ['0' => 4, '1' => 5, '2' => 6];
$merged_array = [];
for($i=0;$i<count($first);$i++)
{
array_push($merged_array,[$first[$i],$second[$i]]);
}
$final = [];
$ab = ['a','b'];
foreach($merged_array as $arr)
{
array_push($final,array_combine($ab, $arr));
}
print_r($final);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.