有一个像
这样的字符串1,36,42,43,45,69,Standard,Executive,Premium
我想在数组中转换它,但只需要数值
Array
(
[0] => 1
[1] => 36
[2] => 42
[3] => 43
[4] => 45
[5] => 69
)
不是数组中的所有字符串值。
答案 0 :(得分:4)
使用array_filter
,explode
和is_numeric
函数的简单和简短解决方案:
$str = "1,36,42,43,45,69,Standard,Executive,Premium";
$numbers = array_filter(explode(",", $str), "is_numeric");
print_r($numbers);
输出:
Array
(
[0] => 1
[1] => 36
[2] => 42
[3] => 43
[4] => 45
[5] => 69
)
答案 1 :(得分:2)
print_r(array_filter(
explode(',', '1,36,42,43,45,69,Standard,Executive,Premium'),
'ctype_digit'
));
答案 2 :(得分:0)
<?php
$array = array('1','36','42','43','45','69','Standard','Executive','Premium');
foreach($array as $value) if (is_integer($value)) $new_array[] = $value;
print_r($new_array);
?>
[编辑]哦,是的,我其实更喜欢你的版本RomanPerekhrest&amp; u_mulder:p
答案 3 :(得分:0)
看一下附件摘录:
请看看演示:https://eval.in/593963
<?php
$c="1,36,42,43,45,69,Standard,Executive,Premium";
$arr=explode(",",$c);
foreach ($arr as $key => $value) {
echo $value;
if (!is_numeric($value)) {
unset($arr[$key]);
}
}
print_r($arr);
?>
输出:
Array
(
[0] => 1
[1] => 36
[2] => 42
[3] => 43
[4] => 45
[5] => 69
[6] => Standard
[7] => Executive
[8] => Premium
)
Array
(
[0] => 1
[1] => 36
[2] => 42
[3] => 43
[4] => 45
[5] => 69
)
答案 4 :(得分:0)
Tra this:
$string = "1,36,42,43,45,69,Standard,Executive,Premium";
print_r(array_filter(explode(',', $string), 'is_numeric'));