开发者

How to update a multi-array value?

I have this multidimension array in which I need to update a value. What would be the best way to do so? I tried it with 2 foreach loops but wasn't sure if that was the rig开发者_运维技巧ht approach.

Here is the array in question. I need to update the dollar amount on each sub array (i.e. add 3 to it).

array(6) { ["Ground"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "13.63" } 
           ["3 Day Select"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "25.26" } 
           ["2nd Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "32.43" } 
           ["Next Day Air Saver"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "63.00" } 
           ["Next Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "68.65" } 
           ["Next Day Air Early AM"]=> array(2) { [0]=> string(3) "USD" [1]=> string(6) "103.68" } } 


Your foreach loop approach would be correct, unless you expect the data format to change e.g. to have more nested levels. If that were the case, then a recursive function would be best suited.

Also, if the data is expected to remain uniform, you could do this:

foreach( $my_array as $index => $row ){
  $my_array[$index][1] += 3;
}

cheers!


foreach ($arr as $k=>$row) {
 $arr[$k][1] = floatval($row[1]) + 3;
}


foreach ($array as &$subarray) {
  foreach ($subarray as $key=>&$value) {
    // do whatever you want with $value
    // ...
    $value = 'something else'; // example
    }
  }


Try this:

<?php

foreach($first_array as $first_dem_key)
  $first_array[$first_dem_key][1] = $first_array[$first_dem_key][1] + 3;

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜