dqlk31541 2018-07-23 02:38
浏览 31
已采纳

无法从多维数组中删除空键

I am trying to delete array elements from an array using array_filter function. It's working fine but there is always ONE element that is not removed.

The array is constructed with array_combine using one simple array and other built with array_chunk.

Here is my code:

$arr_a = array("AAA","","CCC","");

$arr_b = array("a1","b1","a2","b2","a3","b3","a4","b4");

$arr_c = array_chunk($arr_b,2);

$c = array_combine($arr_a,$arr_c);

$limpn_url = array_filter($c);

If I'd get an error I would not bother to post here a question. But there is no error returning.

When making print_r($limpn_url); the output is: Array ( [AAA] => Array ( [0] => a1 [1] => b1 ) [] => Array ( [0] => a4 [1] => b4 ) [CCC] => Array ( [0] => a3 [1] => b3 ) )

*note the [] => Array ( [0] => a4 [1] => b4 ) That shouldn't be there. Other empty elements were deleted correctly...

  • 写回答

1条回答 默认 最新

  • doumei1908 2018-07-23 05:13
    关注

    You can use some array functions to remove keys that is empty.

    $arr_a = array("AAA","","CCC","");
    
    $arr_b = array("a1","b1","a2","b2","a3","b3","a4","b4");
    
    $arr_c = array_chunk($arr_b,2);
    
    $c = array_combine($arr_a,$arr_c);
    
    $limp= array_filter($c);
    
    $filteredkeys = array_filter(array_keys($limp)); // here i remove the "" key
    
    $filtered = array_intersect_key($limp, array_flip($filteredkeys)); // since $filterdkeys is values i need to flip it and intersect with $limp
    var_dump($filtered);
    

    output:

    array(2) {
      ["AAA"]=>
      array(2) {
        [0]=>
        string(2) "a1"
        [1]=>
        string(2) "b1"
      }
      ["CCC"]=>
      array(2) {
        [0]=>
        string(2) "a3"
        [1]=>
        string(2) "b3"
      }
    }
    

    https://3v4l.org/miNeW

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料