dongxiezhi0590 2016-05-21 20:49
浏览 43
已采纳

具有相同名称的多维数组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?

  • 写回答

1条回答 默认 最新

  • dongyong5912 2016-05-21 20:59
    关注

    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'] 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度