dpruwm6206 2014-11-10 22:36
浏览 78
已采纳

将多个数组合并为一个覆盖空单元格

I have 5 different arrays that all have the same length (5) but each of the 5 arrays only have 1 value and 4 blank ones. How would I combine the 5 arrays into 1 excluding the empty cells:

Array
(
    [0] => 
    [1] => 5.0
    [2] => 
    [3] => 
    [4] => 
)
Array
(
    [0] => SC28
    [1] => 
    [2] => 
    [3] => 
    [4] => 
)
Array
(
    [0] => 
    [1] => 
    [2] => 
    [3] => Intel(R) Xeon(R) CPU           E5345  @ 2.33GHz
    [4] => 
)
Array
(
    [0] => 
    [1] => 
    [2] => 1999
    [3] => 
    [4] => 
)
Array
(
    [0] => 
    [1] => 
    [2] => 
    [3] => 
    [4] => VMWare
)

to combine into one array like so:

Array
(
    [0] => SC28
    [1] => 5.0
    [2] => 1999
    [3] => Intel(R) Xeon(R) CPU           E5345  @ 2.33GHz
    [4] => VMWare
)
  • 写回答

1条回答 默认 最新

  • dowdw44426 2014-11-10 22:39
    关注

    You can use array_merge (or perhaps array_replace) and array_filter:

    <?php
    
    $array1 = array('Hello', null, 'world', '');
    $array2 = array(0, 0, 'Saluton', '', 'mondo');
    $array3 = array();
    
    $total = array_filter(array_merge(
        $array1, $array2, $array3)
    );
    
    print_r($total);
    

    yields:

    Array
    (
    [0] => Hello
    [2] => world
    [6] => Saluton
    [8] => mondo
    )
    

    Notice that the array has been renumbered, and that all values equivalent to false (i.e. null, the empty string, zero, boolean false) have been expunged.

    If you want to keep some values, you need to pass to array_filter a suitable callback that will return false only in those cases you supply.

    If you want to exactly slide together the arrays, you can use array_replace and filter individually the arrays.

    print_r(array_replace(
        array_filter(array( null, '5.0', null, null, null)),
        array_filter(array( 'SC28', null, null, null, null)),
        array_filter(array( null, null, null, 'Xeon', null))
    ));
    

    This will yield:

    Array
    (
        [1] => 5.0
        [0] => SC28
        [3] => Xeon
    )
    

    which using ksort:

    Array
    (
    [0] => SC28
    [1] => 5.0
    [3] => Xeon
    )
    

    Notice that the missing keys are still missing (if you supply all arrays, you will get your desired result). Notice, however, that with this second approach if two keys in two arrays have the same value, then the latter will overwrite the former.

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

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接