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

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

问题描述:

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
)

我有5个不同的数组,它们都具有相同的长度(5)但是5个数组中的每一个只有1个值 和4个空白的。 如何将5个数组合并为1除了空单元格: p>

  Array 
(
 [0] => 
 [1] => 5.0 \  n [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] => \  n [1] => 
 [2] => 1999 
 [3] => 
 [4] => 
)
Array 
(
 [0] => 
  [1] => 
 [2] => 
 [3] => 
 [4] => VMWare 
)
  code>  pre> 
 
 

组合成一个数组如下: p>

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

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.