dozc58418381 2017-06-02 06:38
浏览 67
已采纳

在PHP中跳过特定数组项的Implode数组

I am trying to implode array with skipping specific value.

My array is:

$unit = array("123","56","0","1","10","965","65","0"," ","63");

From above array I don't want 0(zero) and blank value while imploding, I tried this:

$implode1 = implode(",", array_filter($unit));

Output : 123,56,1,10,965,65, ,63 (Skipping 0 but not blank value)

I tried callback method of array_filter function

Below example, I tried to implode array and don't want 0, 1 and blank value

$implode1 = implode(",", array_filter($unit,function($v,$k){
    return $v != " " || $v != '1' || $v != '0';
},ARRAY_FILTER_USE_BOTH));

output : 123,56,0,1,10,965,65,0, ,63

Can anyone help me Where am i wrong in both methods?

  • 写回答

1条回答 默认 最新

  • dpb35161 2017-06-02 06:40
    关注

    Use && instead of ||:

    $implode1 = implode(",", array_filter($unit,function($v,$k){
        return $v != " " && $v != '1' && $v != '0';
    },ARRAY_FILTER_USE_BOTH));
    

    But in your case it's better to convert values to int and check:

    $implode1 = implode(",", array_filter($unit,function($v,$k){
        return (int)$v > 1;
    },ARRAY_FILTER_USE_BOTH));
    

    Here zeroes and empty values (which will be converted to zero) or even non-numeric values (which will be converted to zero also) will be skipped. And as you don't need 1 too I added greater than check.

    Also as you don't use $k in your function - you can skip it and ARRAY_FILTER_USE_BOTH parameter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?