0

How can I do to merge "artist" value with "title" value in one value?. I'm using PHP 5.2.4 if that helps.

I have this array

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
        )

)

The expected output would be like this, just show element "title" with twice values:

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 Answers 2

2

Try this:

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

mainArr is the array declared above.

p.s. I have not tested this code yet

Sign up to request clarification or add additional context in comments.

1 Comment

Updated the answer as i forgot to replace the existing array values wuth the updated one in my previous answer
2

Try this:

$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']);
}

1 Comment

My bad! I've edited it to $arr as &$a and it works fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.