简体   繁体   中英

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

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

$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)

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM