合并数组并修改或追加新元素

时间:2012-12-11 10:53:29

标签: php arrays multidimensional-array

<?php 
$followed = Array(
    0=>array(
            'label' =>"label0",
            'id_poste'=>1,
            'id_part'=>11,
            'date'=>'9/12/21012'
    ),
    1=>array(
            'label' =>"label1",
            'id_poste'=>2,
            'id_part'=>12,
            'date'=>'10/13/21012'
            )
);

$unfollowed = Array(
    0=>array(
            'label' =>"New label",
            'id_poste'=>1,
            'id_part'=>11           
    )
);

执行此操作以合并两个阵列。

$result = array_merge($followed, 
            array_udiff($unfollowed, $followed, 
                        function($a,$b){
                            return strcmp($a['label'],$b['label']);
                        }
           )
);

我想要result

    Array
(
    [0] => Array
        (
            [label] => label0
            [id_poste] => 1
            [id_part] => 11
            [date] => 9/12/21012
        )

    [1] => Array
        (
            [label] => label1
            [id_poste] => 2
            [id_part] => 12
            [date] => 10/13/21012
        )

    [2] => Array
        (
            [label] =>(A)New label /*concatenate with (A)*/
            [id_poste] => 1
            [id_part] => 11,
            [date]=>'--/--/----' /* Append new element with that format*/
        )

)

?>

1 个答案:

答案 0 :(得分:1)

只需添加以下代码即可。

for($i=0;$i<count($unfollowed);$i++)
{
    $unfollowed[$i]['label'] ='(A)'.$unfollowed[$i]['label'];  
    $unfollowed[$i]['date'] ='--/--/----';
}
$result = array_merge($followed, $unfollowed);