【问题标题】:How can i select array elements what name contains numbers? [duplicate]如何选择名称包含数字的数组元素? [复制]
【发布时间】:2020-11-10 17:57:28
【问题描述】:

起初,我是初学者。

我想将数组中的元素推送到另一个不包含数字的数组

我有一个数组1:

0 => string '142221A' (length=7)
  1 => string 'hOUSES' (length=6)
  2 => string 'bOOKS' (length=5)
  3 => string 'sHOES' (length=5)
  4 => string '92921' (length=5)
  5 => string '12231' (length=5)
  6 => string 'cARS' (length=4)
  7 => string 'tOYS' (length=4)

我想要这样的输出,array2:

  0 => string 'hOUSES' (length=6)
  1 => string 'bOOKS' (length=5)
  2 => string 'sHOES' (length=5) 
  3 => string 'cARS' (length=4)
  4 => string 'tOYS' (length=4)

我不想要一个解决方案,我想要它的方法。

【问题讨论】:

  • array_filter() 与检查值是否包含数字的回调函数一起使用。
  • 你有很多悬而未决的问题,可能值得回顾其中一些并在适当的时候关闭它们 - meta.stackexchange.com/questions/5234/…

标签: php arrays sorting select


【解决方案1】:

在 PHP 中你可以使用is_numeric() 方法来检查字符串是否只是一个数字,方法如下:

$elements = ['142221A','hOUSES','bOOKS','sHOES','92921','12231','cARS','tOYS'];
$string_array = [];
foreach ($elements as $element) {
    if(!is_numeric($element)) {
        array_push($string_array, $element);
    }
}
print_r($string_array);

但是,如果您想过滤数组的元素以仅包含其中没有任何数值的元素,请使用以下方式:

$elements = ['142221A','hOUSES','bOOKS','sHOES','92921','12231','cARS','tOYS'];

$just_string = [];

foreach ($elements as $element) {
    //it will check for the element which has a digit number inside of it or not
   //if it doesn't contain any number then it will be added to new array
    if(preg_match('~[0-9]~', $element) != 1){
        array_push($just_string, $element);
    }
}

print_r($just_string);

【讨论】:

  • 谢谢!但使用这种方法,第一个“142221A”进入新阵列。有数字和一个字符。这是我真正的问题。
  • 因为第一个元素不是数字而是数字与字符串的组合
  • 我编辑了代码并为问题添加了第二个解决方案,只过滤没有任何数字字符的字符串。
  • 完美,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多