我有一个脚本,它自带的一个这样的数组:从PHP数组中删除不同条目的特定部分?
[0] => 1_Result1
[1] => 2_Result2
[2] => 3_Result3
但我想它出来是这样的:
[0] => Result1
[1] => Result2
[2] => Result3
如何才能做到这一点?
我有一个脚本,它自带的一个这样的数组:从PHP数组中删除不同条目的特定部分?
[0] => 1_Result1
[1] => 2_Result2
[2] => 3_Result3
但我想它出来是这样的:
[0] => Result1
[1] => Result2
[2] => Result3
如何才能做到这一点?
foreach ($array as $key => $item) {
//Cut 2 characters off the start of the string
$array[$key] = substr($item, 2);
}
,或者如果你想更看中并从_
切断:
foreach ($array as $key => $item) {
//Find position of _ and cut off characters starting from that point
$array[$key] = substr($item, strpos($item, "_"));
}
这将在PHP 4的任何版本和5
那么它可以帮助了解更多关于如何过滤阵列以及如何形成阵列的特定规则,但要回答您的具体问题:
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);
这里:
<?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例)
'$ var = end(explode('_',$ result));' – user1477388 2013-03-19 20:36:00
Man,user1477388对于这个简单的解决方案,我无法感谢你! – 2013-03-19 20:43:40
但是,你可以感谢我:通过upvoting!你非常欢迎:) – user1477388 2013-03-19 20:47:50