duanmeng9336 2014-12-01 11:47
浏览 122
已采纳

如何从逗号分隔的数字列表中删除某个数字

I have this comma delimited list 0,0,0,0,5,0,7,8,9,10 and i would like to get rid of the number zero represented as a number on its own right and not the zero in 10.

The list is represented in the variable $str and this is the code i am trying to remove the zero with.

$str;

$myArray = explode(',', $str);

if (($key = array_search('0', $myArray)) !== false) {
    unset($myArray[$key]);
}
print_r($myArray);
$csv = implode(', ', $myArray);
echo $csv;

but this gives 0, 0, 0, 5, 0, 7, 8, 9, 10

This code does not do the job as i would have liked.What can i do to get rid of the zeros?.

  • 写回答

2条回答 默认 最新

  • duanchifo2866 2014-12-01 11:50
    关注

    array_filter comes to the rescue:

    $myArray = explode(',', '0,0,0,0,5,0,7,8,9,10');
    print_r(array_filter($myArray, function($el) { return $el; }));
    // ⇒ 
    /*
    Array
    (
        [4] => 5
        [6] => 7
        [7] => 8
        [8] => 9
        [9] => 10
    )
    */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?