Artisan
Artisan

Reputation: 4112

How to replace value inside an array?

I have an array as shown below.

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

If I wanted to replace "order_id" of both elements of this array to a new value before saving to the database, what array function or technique can I use?

Thanks.

Upvotes: 0

Views: 108

Answers (2)

Ascherer
Ascherer

Reputation: 8083

Take a look at array_walk:

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

A simple foreach could work too.

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

Upvotes: 2

j08691
j08691

Reputation: 207901

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

Upvotes: 0

Related Questions