如何将2个数组合并为一个唯一值

时间:2013-03-20 08:36:23

标签: php arrays

我有两个像这样的数组

array (
[0] => Array
    (
        [search_terms] => Big Black Gay
        [searches] => 1
    )

[1] => Array
    (
        [search_terms] => Men Seeking Men Personals
        [searches] => 1
    )
)

像这样的另一个数组

   array (
   [0] => Array
    (
        [search_terms] => Men Seeking Men Personals
        [clicks] => 1
    )
   )

如何在不使用任何循环的情况下合并上面两个数组?任何PHP功能都可用于此?我需要这种出局

Array
(
[0] => Array
    (
        [search_terms] => Big Black Gay
        [searches] => 1
        [clicks] => 0
    )

[1] => Array
    (
        [search_terms] => Men Seeking Men Personals
        [searches] => 1
        [clicks] => 1
    )

)

2 个答案:

答案 0 :(得分:5)

查看array_merge

var_dump(array_merge($array_one,$array_two));

答案 1 :(得分:2)

你可以尝试

$data = array(
        0 => array(
                'search_terms' => 'Big Black Gay',
                'searches' => 1
        ),
        1 => array(
                'search_terms' => 'Men Seeking Men Personals',
                'searches' => 1
        )
);

$combine = array(
        0 => Array(
                'search_terms' => 'Men Seeking Men Personals',
                'clicks' => 1
        )
);

foreach ( $data as &$item ) {
    foreach ( $combine as $new ) {
        if ($item['search_terms'] == $new['search_terms'])
            $item['clicks'] = $new['clicks'];
    }

    if (! isset($item['clicks']))
        $item['clicks'] = 0;
}

print_r($data);

输出

Array
(
    [0] => Array
        (
            [search_terms] => Big Black Gay
            [searches] => 1
            [clicks] => 0
        )

    [1] => Array
        (
            [search_terms] => Men Seeking Men Personals
            [searches] => 1
            [clicks] => 1
        )

)