如何替换数组中的值?

时间:2013-08-15 16:15:11

标签: php arrays

我有一个如下所示的数组。

array (size=2)
    '1S1' =>
      array (size=8)
        'order_id' => int 0
        'item_id' => int 1
        'special_desc' => string 'Special XXX' (length=11)
        'qty' => int 2
        'price' => int 50
        'amount' => int 0
        'created_at' => int 1376580193
        'updated_at' => int 1376580193
    '1S2' =>
      array (size=8)
        'order_id' => int 0
        'item_id' => int 2
        'special_desc' => string 'Special YYY' (length=11)
        'qty' => int 3
        'price' => int 150
        'amount' => int 0
        'created_at' => int 1376580193
        'updated_at' => int 1376580193

如果我想在保存到数据库之前将此数组的两个元素的“order_id”替换为新值,我可以使用哪种数组函数或技术?

感谢。

2 个答案:

答案 0 :(得分:2)

看看array_walk

$array = array_walk( $array, function( $subArray ) {
    $subArray[ 'order_id' ] = 'someNewValue';
} );

简单foreach也可以。

// Noting the '&' by reference call
foreach( $array as &$subArray ) {
    $subArray[ 'order_id' ] = 'someNewValue';
}
// Or
foreach( $array as $key => $value ) {
   $array[ $key  ][ 'order_id' ] = 'someNewValue';
}

答案 1 :(得分:0)

$array_name['1S1']['order_id'] = some value;
$array_name['1S2']['order_id'] = some value;