将数组附加到多维数组,保留键

时间:2017-12-22 02:20:24

标签: php arrays

在PHP中,我有一个名为$ items的数组:

Array
(
    [9] => Array
    (
        [id] => 9
        [title] => Fujifilm XE-1 digital camera
        [uri] => fujifilm-xe-1-digital-camera
        [url] => items/fujifilm-xe-1-digital-camera/9
        [cat_id] => 03.01.01.01
    )
)

和一个名为$ item_photos的数组:

Array
(
    [photos_dir] => ../items/item-images/L1/009/
    [photos] => Array
    (
        [0] => ../items/item-images/L1/009/01xs.jpg
    )

    [main_photos] => Array
    (
        [x_small] => ../items/item-images/L1/009/01xs.jpg
        [small] => ../items/item-images/L1/009/01s.jpg
        [medium] => ../items/item-images/L1/009/01m.jpg
        [large] => ../items/item-images/L1/009/01l.jpg
    )

我想将项目照片附加到items数组,以便它成为一个像这样的大数组(保留数字9键):

Array
 (
     [9] => Array
         (
             [id] => 9
             [title] => Fujifilm XE-1 digital camera
             [uri] => fujifilm-xe-1-digital-camera
             [url] => items/fujifilm-xe-1-digital-camera/9
             [cat_id] => 03.01.01.01
             [photos_dir] => ../items/item-images/L1/009/
             [photos] => Array
             (
                  [0] => ../items/item-images/L1/009/01xs.jpg
             )

             [main_photos] => Array
             (
                  [x_small] => ../items/item-images/L1/009/01xs.jpg
                  [small] => ../items/item-images/L1/009/01s.jpg
                  [medium] => ../items/item-images/L1/009/01m.jpg
                  [large] => ../items/item-images/L1/009/01l.jpg
             )
    )

我试过array_push($items, $item_photos);,但它没有给我正确的结果。

1 个答案:

答案 0 :(得分:2)

这是一个尝试的选项:

$items[9] = array_merge( $items[9], $item_photos );

因此它将$ items [9]替换为一个合并数组,它结合了$ items [9]和$ item_photos。