我有一个脚本,可以生成这样的数组:
[0] => 1_Result1
[1] => 2_Result2
[2] => 3_Result3
但我希望它像这样出来:
[0] => Result1
[1] => Result2
[2] => Result3
如何才能做到这一点?
好吧,了解有关如何过滤数组及其形成方式的更具体规则可能会有所帮助,但要回答您的具体问题:
PHP 5.4:
array_map(function ($elem) { return explode('_', $elem)[1]; }, $arr)
PHP 5.3:
array_map(function ($elem) {
$elem = explode('_', $elem);
return $elem[1];
}, $arr);
foreach ($array as $key => $item) {
//Cut 2 characters off the start of the string
$array[$key] = substr($item, 2);
}
or if you want to be more fancy and cut off from the _
:
foreach ($array as $key => $item) {
//Find position of _ and cut off characters starting from that point
$array[$key] = substr($item, strpos($item, "_"));
}
This will work in any version of PHP 4 and 5.
这里:
<?php
$results = array( "1_result1", "2_result2", "3_result3", "4_reslut4");
$fixed_results = array();
foreach ($results as $result)
{
$fixed_results[]= substr($result, 2);
}
print_r($fixed_results);
?>
将返回
Array
(
[0] => result1
[1] => result2
[2] => result3
[3] => reslut4
)
警告:这仅在您知道要删除的前缀的大小时才有效(在这种情况下为 2)