给定一个数组数组,如何从每个值中去掉子串“GB”?

给定一个数组数组,如何从每个值中去掉子串“GB”?

问题描述:

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?

我的数组中的每个项目都是一个大约5个数值的数组。其中一些是以“GB”结尾的数字 ..我需要相同的数组,但是“GB”被剥离,只留下数字。 p>

所以我需要遍历整个数组,在每个子数组上取每个值并去掉 来自它的字符串“GB”并从输出中创建一个新数组。 p>

任何人都可以推荐并采用有效的方法吗? p> div>

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