php连接数组的两个元素

时间:2015-04-08 04:37:09

标签: php arrays string algorithm multidimensional-array

我有这个数组

$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);

我只想将namefamily合并到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);

Online Demo

有更好的方法吗?

4 个答案:

答案 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
}

Sample Output

答案 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
        )

)

阅读更多内容:

  

http://php.net/array_map

答案 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"];
}