具有相同名称的多维数组PHP

Got a small question. Why this piece of code does only returns one package?

# Packages data
'packages' => [
    'package' => [
        'height' => '100',
        'width' => '200',
    ],
    'package' => [
        'height' => '1300',
        'width' => '2040',
    ],
    'package' => [
        'height' => '1200',
        'width' => '2020',
    ],
]

When I change the names to: packages_1, packages_2, packages_3 they output correctly but when I give them the same name it does only output one package. Is there any way to solve this?

It's because the associative array in PHP is a map so each key must be unique within the same array. You can fix this using one the these method:

  1. Give each of the package keys a unique name (like you've already mentioned in your question).

For example:

'packages' => [
    'package_1' => [
        'height' => '100',
        'width' => '200',
    ],
    'package_2' => [
        'height' => '1300',
        'width' => '2040',
    ],
    'package_3' => [
        'height' => '1200',
        'width' => '2020',
    ],
]
  1. Omit the key entirely and you'll have to access them using indexes.

For example:

'packages' => [
    [
        'height' => '100',
        'width' => '200',
    ],
    [
        'height' => '1300',
        'width' => '2040',
    ],
    [
        'height' => '1200',
        'width' => '2020',
    ],
]

And to access the values:

$myvariable['packages'][0]['height']