我有以下数组。
Array(
[deselected_attachment_ids] => Array
(
[0] => 16883477_12869438
[1] => 16883478_12869439
)
)
array = array( 12869438,12869439); 所需的输出
我使用了以下代码。
$implodeArray = implode(',',$testArray);
它给了我警告
Array to string conversion
我应该如何获得所需的输出数组?
使用爆炸将字符串分成两部分并得到第二部分
$res = array_map(function($x) { return explode('_', $x)[1]; },
$arr['deselected_attachment_ids']);
print_r($res);
你可以让
preg_replace()
帮你遍历数组并删除不需要的部分。 虽然正则表达式并不以速度快而闻名,但它是一种直接的单一功能解决方案。
代码:(演示)
$array=['deselected_attachment_ids'=>['16883477_12869438','16883478_12869439']];
$result=preg_replace('/^\d+_/','',$array['deselected_attachment_ids']);
var_export($result);
输出:
array (
0 => '12869438',
1 => '12869439',
)
或者您可以使用带有
foreach
的 explode()
循环:(演示)
$array=['deselected_attachment_ids'=>['16883477_12869438','16883478_12869439']];
foreach($array['deselected_attachment_ids'] as $v){
$result[]=explode('_',$v)[1];
}
var_export($result);
// same result
最后,如果您不想使用正则表达式,并且不想在每次迭代时生成临时数组(来自
explode()
调用),则可以使用 substr()
和 strpos()
。
$array=['deselected_attachment_ids'=>['16883477_12869438','16883478_12869439']];
foreach($array['deselected_attachment_ids'] as $id){
$result[]=substr($id,strpos($id,'_')+1);
}
var_export($result);