PHP Complete sub array with the same number of elements

124 views Asked by At

I have an array as following.

Array ( 
    [A] => Array ( 
             [y] => 2014-11-26 
             [x] => 1 
             [zzz] => 2 
             [ww] => 1 ) 
    [B] => Array ( 
             [y] => 2014-11-27 
             [zzz] => 2 ) 
    [C] => Array ( 
             [y] => 2014-11-29 
             [ww] => 2 ) 
 ) 

The sub array 'A' has four elements while other sub arrays have only two elements. I would like to fill those other sub array with the same elements of array A with the value 0 so that I get a new array as following.

Array ( 
    [A] => Array ( 
             [y] => 2014-11-26 
             [x] => 1 
             [zzz] => 2 
             [ww] => 1 ) 
    [B] => Array ( 
             [y] => 2014-11-27 
             [x] => 0
             [zzz] => 2 
             [ww] => 0 ) 
    [C] => Array ( 
             [y] => 2014-11-29 
             [x] => 0
             [zzz] => 0 
             [ww] => 2 ) 
 ) 

Below is my algorithme. Because I am a junior developer I am looking for a better algorithme to learn more.

    $allArrayKey = array_keys($array); 

    $mostElement[0] = 0;
    foreach($allArrayKey as $value) {

        if($mostElement[0] < count($array[$value])) {
            $mostElement[0] = count($array[$value]);
        }

    }

    foreach($allArrayKey as $arr) {           
        if(count($array[$arr]) < $mostElement[0]) {
            foreach ($allArrayKey as $xx) {
                if(!array_key_exists($xx, $array[$arr])) {
                    $array[$arr][$xx] = '0';
                }
            } 
        }
    }

How can I do that in PHP?

2

There are 2 answers

0
Naruto On

So as I said get all keys from array A:

$keys = array_keys($array['A']);

$keys is now an array with all they keys. Now the only thing you need todo is loop over your entire array and loop over the keys tocheck if they exists..

foreach($array as &$arr){
    foreach($keys as $key){
        if(!array_key_exists($key, $arr)){
            $arr[$key] = 0;
        }
    }
}
2
georg On

Create a dummy array any_key => 0 and add it to each subarray:

$a = array(
    array('x' => 1, 'y' => 2, 'z' => 3, 'w' => 4),
    array('x' => 11, 'y' => 22, ),
    array('x' => 111, 'y' => 222),
);

$dummy = array_combine(
    array_keys($a[0]),
    array_fill(0, count($a[0]), 0)
);

foreach($a as &$v)
    $v += $dummy;

print_r($a);

If your php doesn't support array_combine use a loop to initialize $dummy:

foreach($a[0] as $k => $_)
    $dummy[$k] = 0;

Finally, to calculate a union of keys from all subarrays instead of using first item's keys, init $dummy like this:

foreach($a as $v)
    foreach($v as $k => $_)
        $dummy[$k] = 0;