0

I have a multidimensional array. The arrays will have different lengths and seldom will they have the same length. My problem here is how can I make it so that the arrays will all share the length of the array with the biggest size?

My Array:

Array
(
    [1] => Array
        (
            [Session 2] => Beer
            [Food] => Chicken
            [Drink] => Beer
        )

    [2] => Array
        (
            [Session 2] => Tea
            [Food] => Aaaa
            [Drink] => Ddd
            [Cake] => Weee
            [Brownies] => Rrrr
        )

)

Expected output:

Array
(
    [1] => Array
        (
            [Session 2] => Beer
            [Food] => Chicken
            [Drink] => Beer
            [Cake] => ''
            [Brownies] => ''
        )

    [2] => Array
        (
            [Session 2] => Tea
            [Food] => Aaaa
            [Drink] => Ddd
            [Cake] => Weee
            [Brownies] => Rrrr
        )

)

The array size is not limited to only two arrays. Is this even possible and if so how?

I only want to copy the array keys and not the values its main purpose here is for presenting the content of the array in a table.

magicianiam
  • 1,474
  • 7
  • 33
  • 70

3 Answers3

6

Here's one option, where you build an array of all possible array keys, then loop over your original array and set empty strings to the keys that don't exist yet:

// find all possible keys
$keys = [];
foreach ($array as $entry) {
    $keys = array_merge($keys, array_keys($entry));
}

// pad missing keys with an empty string
foreach ($array as &$entry) {
    foreach ($keys as $key) {
        if (!isset($entry[$key])) {
            $entry[$key] = '';
        }
    }
}
scrowler
  • 24,273
  • 9
  • 60
  • 92
  • 1
    You don't need the inner loop + the if(). Use array_replace(keys, entry) – Andreas Nov 13 '18 at 09:33
  • @Andreas good point - `$keys = ['Foo' => ''];` then `$entry = array_replace($entry, $keys)` – scrowler Nov 13 '18 at 09:35
  • thank you. will give this a try but what does this line mean? `foreach ($array as &$entry) {` the `&$entry` – magicianiam Nov 13 '18 at 09:37
  • `&` means "modify by reference" - usually loops will give you variables that only last for the scope of the loop construct. By assigning reference, you are saying that any modifications to `$entry` within the loop will propagate back into the original array. You can also do `foreach ($array as $key => $entry) {` and then assign via `$entry[$key] = ...` – scrowler Nov 13 '18 at 09:40
  • 1
    I generally try to avoid modify by reference in loops because of [the weird way PHP handles references](https://stackoverflow.com/questions/3307409/php-pass-by-reference-in-foreach). Even though it's a bit slower, `array_walk()` accomplishes the same thing without the possibility of weird side effects. – Sam Nov 13 '18 at 09:57
  • 1
    Is it not preferable to also use `array_fill_keys` to just set all the values to the desired ones? So if he wishes to have all the keys and empty values to just do it as `$emptyValuesArray = array_fill_keys(array_keys($targetArray), '');` And avoid the for loops – Diogo Santo Nov 13 '18 at 11:12
1

If the main purpose is to show the data in a table, then you do not need to fill in the missing keys. You can use the isset() or empty() functions to determine whether an array has a given key. So, your table code could look like the following:

<?php
foreach ($rows as $row) {
    echo "<tr>";
    echo "<td>" . (isset($row["Session 2"]) ? $row["Session 2"] : "") . "</td>"; //Old school
    echo "<td>" . ($row["Food"] ?? "") . "</td>"; //PHP 7+
    //remaining rows
    echo "</tr>";
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Sam
  • 178
  • 2
  • 11
  • 1
    The [null coalescing operator](http://php.net/manual/de/migration70.new-features.php#migration70.new-features.null-coalesce-op) could also be used here – Karsten Koop Nov 13 '18 at 09:46
  • @KarstenKoop Thanks, I've updated my answer with some better examples – Sam Nov 13 '18 at 09:52
0

Let's say the array you're talking about is inside a variable $array,

Do this to find the maximum length;

$max = 0;

foreach($array as $index => $value){

    if($index == sizeof($array) - 1){
        break;
    }

    if($index && $max > sizeof($array[$index+1])){
        $max = $max;
    }
    if(!$index && sizeof($value) > sizeof($array[$index+1])){
        $max = sizeof($value);
    }else {
        $max = sizeof($array[$index+1]);
    }
}
scrowler
  • 24,273
  • 9
  • 60
  • 92
Matnex Mix
  • 49
  • 8