合并两个数组元素

时间:2017-04-24 03:57:20

标签: php arrays merge

如何将“艺术家”值与“标题”值合并为一个值?如果有帮助,我正在使用PHP 5.2.4。

我有这个数组

Array
(
    [0] => Array
        (
            [artist] => Narcosis
            [title] => Destruir
            [duration] => 137
            [date] => 1370807642
            [genre_id] => 18
        )

    [1] => Array
        (
            [artist] => Ricardo Palma Fanjul
            [title] => Mutant
            [duration] => 347
            [date] => 1448227909
            [genre_id] => 18
        )

)

预期输出将是这样的,只显示带有两次值的元素“title”:

Array
(
    [0] => Array
        (
            [title] => Narcosis - Destruir
            [duration] => 137
            [date] => 1370807642
            [genre_id] => 18
        )

    [1] => Array
        (
            [title] => Ricardo Palma Fanjul - Mutant
            [duration] => 347
            [date] => 1448227909            
            [genre_id] => 18
        )

)

2 个答案:

答案 0 :(得分:2)

试试这个:

foreach ($mainArr as $index=>$subArr) {
    $subArr['title'] = $subArr['artist'].' - '.$subArr['title'];
    unset($subArr['artist']);
    $mainArr[$index] = $subArr;
}

mainArr是上面声明的数组。

P.S。我还没有测试过这段代码

答案 1 :(得分:2)

试试这个:

$new = array_map(function($v) {
    $v['title'] = $v['artist'].' - '.$v['title'];
    unset($v['artist']);
    return $v;
}, $arr);

OR

foreach ($arr as &$a) {
    $a['title'] = $a['artist'].' - '.$a['title'];
    unset($a['artist']);
}