开发者

Given an array of arrays, how can I strip out the substring "GB" from each value?

开发者 https://www.devze.com 2022-12-29 16:37 出处:网络
Each item in my array is an array of开发者_开发问答 about 5 values.. Some of them are numerical ending in \"GB\".. I need the same array but with \"GB\" stripped out so that just the number remains.

Each item in my array is an array of开发者_开发问答 about 5 values.. Some of them are numerical ending in "GB".. I need the same array but with "GB" stripped out so that just the number remains.

So I need to iterate through my whole array, on each subarray take each value and strip the string "GB" from it and create a new array from the output.

Can anyone recommend and efficient method of doing this?


You can use array_walk_recursive() for this:

array_walk_recursive($arr, 'strip_text', 'GB');

function strip_text(&$value, $key, $string) {
  $value = str_replace($string, '', $value);
}

It's a lot less awkward than traversing an array with its values by reference (correctly).


You can create your own custom function to iterate through an array's value's, check if the substring GB exists, and if so, remove it. With that function you can pass the original array and the function into array_map


// i only did the subarray part
$diskSizes = array("500", "300 GB", "200", "120 GB", "130GB");
$newArray = array();

foreach ($diskSizes as $diskSize) {
    $newArray[] = str_replace('GB', '', $diskSize);


}

// look at the new array
print_r($newArray);


$arr = ...

foreach( $arr as $k => $inner ) {
   foreach( $inner as $kk => &$vv ) {
      $vv = str_replace( 'GB', '', $vv );
   }
}

This actually keeps the original arrays intact with the new strings. (notice &$vv, which means that i'm getting the variable by reference, which means that any changes to $vv within the loop will affect the actual string, not by copying)

0

精彩评论

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