我有这个数组
$MyArray[0]=Array("id"=>1,"name"=>prophet,"family"=>muhammad);
$MyArray[1]=Array("id"=>1,"name"=>imam,"family"=>ali);
$MyArray[2]=Array("id"=>1,"name"=>imam,"family"=>hossein);
我只想将name
和family
合并到fullName
?
我想要这样
$MyArray[0]=Array("id"=>1,"name"=>prophet,"family"=>muhammad,"fullName"=>"prophet muhammad");
$MyArray[1]=Array("id"=>1,"name"=>imam,"family"=>ali,"fullName"=>"imam ali");
$MyArray[2]=Array("id"=>1,"name"=>imam,"family"=>hossein,"fullName"=>"imam hossein");
我可以使用此代码
$count=0;
foreach($MyArray as $R)
{
$result[$count++]=array("name"=>$R["name"],"family"=>$R["family"],"fullName"=>$R["name"]." ".$R["family"]);
}
var_dump($result);
有更好的方法吗?
答案 0 :(得分:4)
只需在当前数组结构中分配新的密钥对值即可。一个简单的foreach就足够了:
$MyArray[0]=Array("id"=>1,"name"=>"prophet","family"=>"muhammad");
$MyArray[1]=Array("id"=>1,"name"=>"imam","family"=>"ali");
$MyArray[2]=Array("id"=>1,"name"=>"imam","family"=>"hossein");
foreach($MyArray as &$arr) {
// ^ reference
$arr['fullName'] = "{$arr['name']} {$arr['family']}";
// ^ new key ^ new value assignment
}
答案 1 :(得分:3)
您可以在代码中使用array_map()
,如下所示:
<?php
$MyArray[0]=Array("id"=>1,"name"=> "prophet", "family"=> "muhammad");
$MyArray[1]=Array("id"=>1,"name"=> "imam", "family"=> "ali");
$MyArray[2]=Array("id"=>1,"name"=> "imam", "family"=> "hossein");
$array = array_map(function($n) {$n['fullName'] = $n['name'] . ' ' . $n['family']; return $n;}, $MyArray);
print_r($array);
输出:
Array
(
[0] => Array
(
[id] => 1
[name] => prophet
[family] => muhammad
[fullName] => prophet muhammad
)
[1] => Array
(
[id] => 1
[name] => imam
[family] => ali
[fullName] => imam ali
)
[2] => Array
(
[id] => 1
[name] => imam
[family] => hossein
[fullName] => imam hossein
)
)
阅读更多内容:
答案 2 :(得分:2)
$MyArray[0]=Array("id"=>1,"name"=>prophet,"family"=>muhammad);
$MyArray[1]=Array("id"=>1,"name"=>imam,"family"=>ali);
$MyArray[2]=Array("id"=>1,"name"=>imam,"family"=>hossein);
$count = count($MyArray);
for ($i = 0; $i < $count; $i++) {
$MyArray[$i]['fullName'] = $MyArray[$i]['name'] . ' ' . $MyArray[$i]['family'];
}
print_r($MyArray);
答案 3 :(得分:2)
您可以使用foreach循环执行此操作。这是一个例子。
$MyArray[0]=Array("id"=>1,"name"=>prophet,"family"=>muhammad);
$MyArray[1]=Array("id"=>1,"name"=>imam,"family"=>ali);
$MyArray[2]=Array("id"=>1,"name"=>imam,"family"=>hossein);
foreach($MyArray as $key=>$myarray){
$MyArray[$key]["fullName"] = $myarray["name"]." ".$myarray["family"];
}