php - Combine multiple arrays into one overwriting empty cells -
i have 5 different arrays have same length (5) each of 5 arrays have 1 value , 4 blank ones. how combine 5 arrays 1 excluding 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 1 array so:
array ( [0] => sc28 [1] => 5.0 [2] => 1999 [3] => intel(r) xeon(r) cpu e5345 @ 2.33ghz [4] => vmware )
you can utilize array_merge
(or perhaps array_replace
) , 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 array has been renumbered, , values equivalent false (i.e. null, empty string, zero, boolean false) have been expunged.
if want maintain values, need pass array_filter
a suitable callback homecoming false
in cases supply.
if want exactly slide together arrays, can utilize array_replace
, filter individually 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 yield:
array ( [1] => 5.0 [0] => sc28 [3] => xeon )
which using ksort
:
array ( [0] => sc28 [1] => 5.0 [3] => xeon )
notice missing keys still missing (if supply arrays, desired result). notice, however, sec approach if 2 keys in 2 arrays have same value, the latter overwrite former.
php arrays
No comments:
Post a Comment