基于key连接2个数组的字符串

时间:2015-11-17 07:58:41

标签: php arrays

所以我在php中组合数组有点困难。所以,假设我有这两个数组

array:4 [▼
  20 => "University"
  21 => "Polic Station"
  22 => "Ambulance"
  1  => "Zoo"
]

array:4 [▼
  20 => "abc"
  21 => "def"
  22 => "ghi"
  1  => "jkl"
]

我如何实际将此结合到此

array:4 [▼
  20 => "abc University"
  21 => "def Polic Station"
  22 => "ghi Ambulance"
  1  => "jkl Zoo"
]

1 个答案:

答案 0 :(得分:5)

结果如下:

$arr = array(
    20=>'University',
    21=>'Polic Station',
    22=>'Ambulance',
    1=>'Zoo');
$arr2= array(
    20=>'abc',
    21=>'def',
    22=>'ghi',
    1=>'jkl');
$arr_out = array();
foreach($arr as $key=>$el) {
    $arr_out[$key] = $arr2[$key] ." ".$el;
}
var_dump($arr_out);

显然,您需要记住检查第二个数组中是否存在密钥,以便在访问该值时不会出错。