[英]How to merge two arrays based on their index php?
I need to merge 2 arrays and i have found lot of examples here on stackoverflow, but nothing has worked for me, in my case, so i explain my case:我需要合并 2 个 arrays 并且我在 stackoverflow 上找到了很多示例,但在我的情况下对我没有任何帮助,所以我解释一下我的情况:
Arrays (can be one, two, or three, or more...): Arrays(可以是一、二、三,或者更多……):
Array ( [0] => name-file_icon_001_00.png-
[1] => name-file_icon_002_00.png-
[2] => name-file_icon_003_00.png- )
Array ( [0] => rel
[1] => rel
[2] => rel )
Or can be two:或者可以是两个:
Array ( [0] => name-file_icon_001_00.png-
[1] => name-file_icon_002_00.png- )
Array ( [0] => rel
[1] => rel )
Or one:或者一个:
Array ( [0] => name-file_icon_001_00.png- )
Array ( [0] => rel )
Need to insert the relative value " [0] => rel
" with " [0] => name-file_icon_001_00.png-
"需要插入相对值“
[0] => rel
”和“ [0] => name-file_icon_001_00.png-
”
Expected result (merged):预期结果(合并):
Array ( [0] => name-file_icon_001_00.png-rel
[1] => name-file_icon_002_00.png-rel
[2] => name-file_icon_003_00.png-rel )
Reading around the web, seems that not exist a native function for make this.阅读 web,似乎不存在用于制作此功能的原生 function。 Please, hope in your help:)
请,希望在你的帮助:)
A simple foreach loop using the index and value parameters will do it in no time使用 index 和 value 参数的简单 foreach 循环将立即完成
Example例子
$a1 = ['name-file_icon_001_00.png-',
'name-file_icon_002_00.png-',
'name-file_icon_003_00.png-'
];
$a2 = ['rel1','rel2','rel3'];
foreach ($a1 as $i => $v){
$new[] = $v . $a2[$i];
}
print_r($new);
RESULT结果
Array
(
[0] => name-file_icon_001_00.png-rel1
[1] => name-file_icon_002_00.png-rel2
[2] => name-file_icon_003_00.png-rel3
)
You can map each array to a function that concatenates them:您可以将每个数组 map 连接到连接它们的 function :
$result = array_map(function($a, $b) { return $a.$b; }, $one, $two);
If you define one array with subarrays then you can unpack that array ...
:如果您使用子数组定义一个数组,那么您可以解压缩该数组
...
:
$array = [$one, $two];
$result = array_map(function($a, $b) { return $a.$b; }, ...$array);
Or for fun, you can extract each column from the subarrays and implode
them:或者为了好玩,您可以从子数组中提取每一列并将它们内
implode
:
$array = [$one, $two];
for($i=0; $a=array_column($array, $i); $i++) {
$result[] = implode($a);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.