我有一个数组并使用
array_filter()
函数过滤值。我在过滤器函数上使用了 echo 来查看过滤后的值是否有效。
$columns = array(
0 => 'ISO',
1 => 'Country',
2 => 'Country Code',
3 => 'Type of number',
4 => 'Voice Enabled',
5 => 'SMS Enabled',
6 => 'MMS Enabled',
7 => 'Domestic Voice Only',
8 => 'Domestic SMS only',
9 => 'Price /num/month',
10 => 'Inbound Voice price/min',
11 => 'Inbound SMS price/msg ',
12 => 'Inbound MMS price/msg ',
13 => 'Beta Status',
14 => 'Address Required',
);
echo '<pre>';
$columns = array_filter($columns, '_filter_column_names');
echo '</pre>';
function _filter_column_names($column_name){
$column_name = str_replace(' /', '_', $column_name);
$column_name = strtolower(str_replace(array(' ', '/'), '_', trim($column_name)));
echo $column_name.'<br>';
return $column_name;
}
echo '<pre>';
print_r($columns);
echo '</pre>';
iso
country
country_code
type_of_number
voice_enabled
sms_enabled
mms_enabled
domestic_voice_only
domestic_sms_only
price_num_month
inbound_voice_price_min
inbound_sms_price_msg
inbound_mms_price_msg
beta_status
address_required
Array
(
[0] => ISO
[1] => Country
[2] => Country Code
[3] => Type of number
[4] => Voice Enabled
[5] => SMS Enabled
[6] => MMS Enabled
[7] => Domestic Voice Only
[8] => Domestic SMS only
[9] => Price /num/month
[10] => Inbound Voice price/min
[11] => Inbound SMS price/msg
[12] => Inbound MMS price/msg
[13] => Beta Status
[14] => Address Required
)
打印数组时,不会保留在函数体中执行的更改。尽管看起来过滤器函数内的数组值过滤正确。
您也可以在这里观看直播http://3v4l.org/SttJ3
我认为你误解了 array_filter 的作用。正如文档所说,它“使用回调函数过滤数组的元素”,这意味着回调应该返回 true/false,具体取决于是否应包含它。
您可能想要使用的是 array_map,它对每个项目运行回调并返回修改后的项目。
你没有正确使用回调,按照PHP官方手册:
迭代数组中的每个值,并将它们传递给回调 功能。如果回调函数返回true,则当前值 from 数组返回到结果数组中。
对于输出数组中不需要的元素,您的回调需要返回 FALSE。
完全放弃使用
array_filter()
,它是完成任务的错误工具。
将所有值转换为小写,然后将所有非字母序列替换为下划线。
代码:(演示)
var_export(
preg_replace(
'/[^a-z]+/',
'_',
array_map('strtolower', $columns)
)
);