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

精氨酸

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

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;
}
尸体

不需要两个循环:

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

或者使用key修改原数组:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章