CMArg
CMArg

Reputation: 1567

Add value to existing array key in foreach loop

I have the following bibliography data in an array (note that fields are in random order - there are others fields as well):

Array
(
    [0] => Array
        (
            ['Pub_Name'] => Nature
            ['Volume'] => 6
            ['Pages'] => 215-217
        )
    [1] => Array
        (
            ['Volume'] => 15
            ['Pages'] => 358-360
            ['Pub_Name'] => Science            
        )
    [2] => Array
        (
            ['Pub_Name'] => PNAS
            ['Pages'] => 17-19            
            ['Volume'] => 22
        )
)     

I want to "merge" those three fields into one, for example ['Pub_Name']=Nature, 6: 215-217. I tried the following whitout success (I guess $Record['Pub_Name'] is the incorrect sintax):

foreach ($MyArray as $Record) {
    foreach ($Record as $key => $values) {
        if ($key=="Volume") {$Volumen=", ".$values;} else {$Volumen="";}
        if ($key=="Pages") {$Paginas=": ".$values;} else {$Paginas="";}
    }

    //This is the line for which I want to know the sintax!!
    $Record['Pub_Name'].=$Volumen.$Paginas;
}

Upvotes: 0

Views: 3880

Answers (7)

FrenchMajesty
FrenchMajesty

Reputation: 1139

This should help:

$combined = [];
foreach($myArray as $pub) {
    $combined.push($pub['Pub_Name'] . ', ' . $pub['Volume'] . ': ' . $pub['Pages']);
}

Upvotes: -1

MarcM
MarcM

Reputation: 2251

Clear way in a single loop. Use sprintf() for easy formatting:

<?php
$src =[ ['Pub_Name' => 'Nature', 'Volume' => '6', 'Pages' => '215-217'],
        ['Volume' => '15', 'Pages' => '358-30', 'Pub_Name' => 'Science'],
        ['Pub_Name' => 'PNAS', 'Pages' => '17-19',  'Volume' => '22']
      ];

foreach ($src as $element) {
    $dest[] = sprintf("%s, %d: %s", 
       $element['Pub_Name'], 
       $element['Volume'], 
       $element['Pages']);
}

var_dump($dest);
?>

And you get:

    array(3) { 
[0]=> string(18) "Nature, 6: 215-217" 
[1]=> string(19) "Science, 15: 358-30" 
[2]=> string(15) "PNAS, 22: 17-19"
 }

Test it here.

Upvotes: 0

Sahil Gulati
Sahil Gulati

Reputation: 15141

PHP code demo

<?php
$array=Array
(
    0 => Array
        (
            'Pub_Name' => "Nature",
            'Volume' => 6,
            'Pages' => "215-217"
        ),
    1 => Array
        (
            'Volume' => 15,
            'Pages' => "358-360",
            'Pub_Name' => "Science"            
        ),
    2 => Array
        (
            'Pub_Name' => 'PNAS',
            'Pages' => "17-19",          
            'Volume' => 22
        )
);
$result=array();
foreach ($array as $data)
{
    $result[]=array('Pub_Name'=>  $data['Pub_Name'].", ".$data["Volume"].": ".$data["Pages"]);

}
print_r($result);

Output:

Array
(
    [0] => Array
        (
            [Pub_Name] => Nature, 6: 215-217
        )

    [1] => Array
        (
            [Pub_Name] => Science, 15: 358-360
        )

    [2] => Array
        (
            [Pub_Name] => PNAS, 22: 17-19
        )

)

Upvotes: 1

Anthony Gray
Anthony Gray

Reputation: 384

There are a few different ways to do this - but one of the more readable ways:

// create a copy of the original - so we aren't looping thru the same array we're updating
$updatedArray = $MyArray;

foreach ($MyArray as $index => $record) {
    $updatedArray[$index]['Pub_Name'] =
        $record['Pub_Name'].  
        ($record['Volume'] ? ', '.$record['Volume'] : ''). 
        ($record['Pages'] ? ': '.$record['Pages']:'');
}

Upvotes: 0

ponury-kostek
ponury-kostek

Reputation: 8060

Use array_map

$in = [
    0 => [
        'Pub_Name' => 'Nature',
        'Volume' => 6,
        'Pages' => '215-217'
    ],
    1 => [
        'Volume' => 15,
        'Pages' => '358-360',
        'Pub_Name' => 'Science',
    ],
    2 => [
        'Pub_Name' => 'PNAS',
        'Pages' => '17-19',
        'Volume' => 22
    ]
];

array_map(function ($item) {
    return $item['Pub_Name'] . ', ' . $item['Volume'] . ': ' . $item['Pages'];
}, $in);

Upvotes: 0

arkascha
arkascha

Reputation: 42885

I guess this is what you are looking for:

<?php
$input = [
    [
        'Pub_Name' => 'Nature',
        'Volume' => '6',
        'Pages' => '215-217'
    ],
    [
        'Volume' => '15',
        'Pages' => '358-30',
        'Pub_Name' => 'Science',
    ],
    [
        'Pub_Name' => 'PNAS',
        'Pages' => '17-19',
        'Volume' => '22'
    ]
];
$output = [];
array_walk($input, function ($entry) use (&$output) {
    $output[] = sprintf(
        '%s, %s: %s',
        $entry['Pub_Name'],
        $entry['Volume'],
        $entry['Pages']
    );
});
print_r($output);

The output of above code obviously is:

Array
(
    [0] => Nature, 6: 215-217
    [1] => Science, 15: 358-30
    [2] => PNAS, 22: 17-19
)

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

No need for two loops:

foreach ($MyArray as $Record) {
    $result[]['Pub_Name'] = "{$Record['Pub_Name']}, {$Record['Pages']}: {$Record['Volume']}";
}

Then you have the new Pub_Name entries in $result.

If you want to modify the original then reference & $Record:

foreach ($MyArray as &$Record) {
    $Record['Pub_Name'] = "{$Record['Pub_Name']}, {$Record['Pages']}: {$Record['Volume']}";
}

Or use the key and modify the original array:

foreach ($MyArray as $key => $Record) {
    $MyArray[$key]['Pub_Name'] = "{$Record['Pub_Name']}, {$Record['Pages']}: {$Record['Volume']}";
}

Upvotes: 2

Related Questions