在foreach循环中为现有数组键添加值

时间:2017-04-04 15:49:16

标签: php arrays

我在数组中有以下参考书目数据(请注意,字段是随机顺序的 - 还有其他字段):

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

我想将这三个字段“合并”为一个,例如['Pub_Name']=Nature, 6: 215-217。我尝试了以下whitout成功(我猜$Record['Pub_Name']是不正确的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;
}

7 个答案:

答案 0 :(得分:2)

不需要两个循环:

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

然后您在Pub_Name中有新的$result条目。

如果您想修改原件,请参考& $Record

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

或者使用密钥并修改原始数组:

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

答案 1 :(得分:0)

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

<强>输出:

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
        )

)

答案 2 :(得分:0)

我想这就是你要找的东西:

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

上述代码的输出显然是:

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

有几种不同的方法可以做到这一点 - 但其中一种方式更具可读性:

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

答案 5 :(得分:0)

单循环中的清晰方式。使用sprintf()可以轻松格式化:

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

你得到:

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

测试here

答案 6 :(得分:-1)

这应该有所帮助:

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