PHP array_map没有返回结果数组

时间:2017-06-08 17:04:37

标签: php array-map

我试图用hypen替换数组值的间距,然后重新收回相同数组的所有值,但在空格中使用hypen。

INPUT:

$gFontsList = array("-1", "Agency FB", "28", "Aharoni Bold", "Bookshelf Symbol", "100", "Bookshelf Symbol", "111", "Browallia New Bol");

function toReplaceSpacing($gFontsListValues, $gFontsListIndex){
   if (gettype($gFontsListValues) === 'string'){
      if(preg_match('/ /',$gFontsListValues)){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
        $gFontsChoiceOrder[] = $gFontsListValues;
      }
    } else {
      $gFontsChoiceOrder[] = $gFontsListValues;
    }
}
$gFontsChoiceOrder = array_map('toReplaceSpacing',$gFontsList);
print_r($gFontsChoiceOrder);

如果我打印它只是NULL。我不知道为什么我没有得到结果阵列?。

2 个答案:

答案 0 :(得分:1)

两个问题:

function toReplaceSpacing($gFontsListValues){
   if (gettype($gFontsListValues) === 'string'){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
   }
   return $gFontsListValues;
}
  1. 您需要返回新值
  2. 回调只接受值,因此只有一个参数
  3. 另外,在更换之前,我没有看到任何检查空间的原因(特别是使用正则表达式),这会使代码更长。

    正如billyonecan在注释中指出的那样,它可以使用匿名函数完成,但此版本不检查字符串,因此可能导致数组,对象等问题:

    $gFontsChoiceOrder = array_map(function($v) {
                                       return str_replace(' ', '-', $v);
                                   }, $gFontsList);
    

    为了将来参考,您可以使用array_walk()和参考:

    修改原始数组
    function toReplaceSpacing(&$gFontsListValues){
       if (gettype($gFontsListValues) === 'string'){
            $gFontsListValues = str_replace(' ','-',$gFontsListValues);
       }
    }
    array_walk($gFontsList, 'toReplaceSpacing');
    

答案 1 :(得分:0)

删除第二个参数False,然后返回一个值https://dev.virtualearth.net/REST/v1/Locations?CountryRegion=us&adminDistrict=CA&locality=Meadow%20Valley&postalCode=95956&addressLine=86%20Oakleaf%20Dr.&output=json&key=BingMapsKey

$gFontsListIndex
相关问题