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?
So as I said get all keys from 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..