以下是我的输入:
$firstname=array
("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana");
$lastname=array
("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");
我需要创建一个数组,它将$ firstname [i]与$ lastname [$ i}连接起来,从而创建一个结合了名字和姓氏的数组。
我的输出如下,但不正确:
<?php
foreach($firstname as $first){
foreach($lastname as $last){
$fullname[]=$first." ".$last;
}
}
print_r($fullname);
?>
我可能不应该使用foreach循环但是我被卡住了。
答案 0 :(得分:1)
假设大小相同的数组:
$firstname=array("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana");
$lastname=array("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");
$size = count($firstname);
for ($i=0; $i < $size; $i++) {
$fullname[]=$firstname[$i]." ".$lastname[$i];
}
答案 1 :(得分:1)
这应该适合你:
(这里我只使用array_map()
遍历两个数组,并将它们连接到$result
数组中)
<?php
$firstname = ["Raj", "Swati", "Kunal", "Hema", "Kareena", "Deepika", "Shilpa", "Amitabh", "Shahrukh", "Kangana"];
$lastname = ["Kumar", "Sharma", "Kapoor", "Malini", "Kapoor", "Padukone", "Shetty", "Amitabh", "Shahrukh", "Kangana"];
$result = array_map(function($v1, $v2){
return "$v1 $v2";
}, $firstname, $lastname);
print_r($result);
?>
输出:
Array ( [0] => Raj Kumar [1] => Swati Sharma [2] => Kunal Kapoor [3] => Hema Malini [4] => Kareena Kapoor [5] => Deepika Padukone [6] => Shilpa Shetty [7] => Amitabh Amitabh [8] => Shahrukh Shahrukh [9] => Kangana Kangana )
答案 2 :(得分:0)
如果您知道两个数组中的数据顺序正确:
$out=[];
foreach($firstname as $key=>$val)
$out[$key] = $val . ' ' . $lastname[$key];
var_dump($out);
答案 3 :(得分:0)
一种方法是使用array_combine
;
$newArr = array_combine($firstname, $lastname);
foreach($newArr as $key => $value){
echo $key." ".$value;
}