简体   繁体   English

在PHP中合并两个或多个数组的值

[英]Merge the values of two or more arrays in php

Someone could be so nice to tell me how to do the following with 2 ore more arrays in PHP: 有人可能很高兴告诉我如何在PHP中使用2个或更多数组来执行以下操作:

array 1 (a,b,c,d)
array 2 (1,2,3,4)

I would like to merge the two arrays in an unique array with the merged values: 我想将两个数组合并为具有合并值的唯一数组:

Result: unique array (a-1,b-2,c-3,d-4) . 结果:唯一array (a-1,b-2,c-3,d-4)

Is there any function that does so? 有没有这样做的功能? I could not find anything in the forum either on the web. 我在网上的论坛上都找不到任何内容。


Thanks for all your answers but I guess that my arrays are a bit more structured because I need the final result for a dropdown field. 感谢您的所有回答,但我想我的数组要结构化一些,因为我需要下拉字段的最终结果。 Now I have these 2 arrays: 现在我有这两个数组:

$array1[] = array( 'text' => $hospital['value'], 'value' => $hospital['value'] );
$array2[] = array( 'text' => $company['value'], 'value' => $company['value'] );

I want to have a final array that contains: Hospital1 - Company1, Hospital2 - Company2, Hospital3 - Company3, etc.. 我想要一个最终的数组,其中包含: Hospital1 - Company1, Hospital2 - Company2, Hospital3 - Company3,等等。

Thanks 谢谢

You can use array_map : 您可以使用array_map

$result = array_map(function ($item1, $item2) {
    return "$item1-$item2";
}, $array1, $array2);

Here is working demo . 这是工作演示

You would have to create a loop to do this manually. 您必须创建一个循环才能手动执行此操作。 it might look something like the following: 它可能类似于以下内容:

$a = array(a,b,c,d);
$b = array(1,2,3,4);
$c = array(); //result set
if(count($a) == count($b)){ // make sure they are the same length
   for($i = 0; $i < count($a); $i++){
      $c[] = $a[$i]."-".$b[$i];
   }
}
print_r($c);

If i understand right, you can use array_combine where array 1 will be the key and array 2 the value. 如果我理解正确,则可以使用array_combine,其中array 1是键,而array 2是值。

Example usage: 用法示例:

$a = array(1,2,3,4);
$b = array(a,b,c,d);

$c = array_combine($a, $b);
var_dump($c);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM