0

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;
}
1

7 Answers 7

2

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']}";
}
Sign up to request clarification or add additional context in comments.

3 Comments

It worked, thanks! And please, what does & account for in your second option?
It's a reference that modifies the array when you modify $Record. Explained here: php.net/manual/en/control-structures.foreach.php
thanks. The warning for unseting $Record of your link also helped me...
1

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
        )

)

Comments

0

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
)

Comments

0

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);

Comments

0

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

Comments

0

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.

1 Comment

Thanks a lot. So many answers in minutes (I've been stuck with this for a long time). Sadly there can be only one accepted answer.
-1

This should help:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.