将数组添加到数组

时间:2017-09-20 07:40:39

标签: php arrays

如何将$ add中的数组添加到我的完整数组中,所以它的数字为[3]:

$add = array('email' => 'email@email.com2', 'm_field_id_9' => 'Name2');

我的阵列打印出来了:

  Array ( 
        [0] => Array ( 
            [email] => email@email.com
            [m_field_id_9] => Name 
        ) 
        [1] => Array ( 
            [email] => email@email.com
            [m_field_id_9] => Name
        ) 
        [2] => Array ( 
            [email] => email@email.com
            [m_field_id_9] => Name 
        )
    ) 

我尝试过array_push(),但我无法添加数组。

5 个答案:

答案 0 :(得分:4)

您可以使用:

$arrayfull[]=$add;

答案 1 :(得分:2)

$fullArray[] = $add;

你可以使用它。

答案 2 :(得分:1)

您可以在PHP中使用array_merge

DISC: - array_merge()函数将一个或多个数组合并为一个数组。

<?php

$array = [
 array('email' => 'email@email.com1', 'm_field_id_9' => 'Name1'),
 array('email' => 'email@email.com2', 'm_field_id_9' => 'Name2')
];

$add = [array('email' => 'email@email.com3', 'm_field_id_9' => 'Name3')];

echo "<pre>";
print_r(array_merge($array, $add));

答案 3 :(得分:0)

理想的情况是简单地使用Square Brackets并指出第3个插槽@index Nr。 2 ....因为你在这里处理一个多维数组......

    $add        = array('email' => 'email@email.com2', 'm_field_id_9' => 'Name2');
    $mainArray  = [
        [
            'email'         => 'email@email.com',
            'm_field_id_9'  => 'Name',
        ],
        [
            'email'         => 'email@email.com',
            'm_field_id_9'  => 'Name',
        ],
        [
            'email'         => 'email@email.com',
            'm_field_id_9'  => 'Name',
        ],
    ];
    // SIMPLY USE THE SQUARE BRACKETS HERE FOR THIS...
    // TO OVERWRITE THE INDEX LOCATION#3 (3RD ARRAY) GO:
    $mainArray[2]    = $add;
    // TO JUST APPEND TO THE END OF THE LAST ITEM THUS CREATING A 4TH SUB-ARRAY, GO:
    $mainArray[]     = $add;

答案 4 :(得分:0)

数组推送应该没问题:

<?php
$items =
[
    [ 
        'email' => 'foo@email.com',
        'name' => 'Foo' 
    ],
    [ 
        'email' => 'bar@email.com',
        'name' => 'Bar'
    ],
    [
        'email' => 'baz@email.com',
        'name' => 'Baz'
    ]
];

$item =
    [
        'email' => 'qux@email.com',
        'name' => 'qux'
    ];

array_push($items, $item);
var_export($items);

输出:

array (
0 => 
array (
    'email' => 'foo@email.com',
    'name' => 'Foo',
),
1 => 
array (
    'email' => 'bar@email.com',
    'name' => 'Bar',
),
2 => 
array (
    'email' => 'baz@email.com',
    'name' => 'Baz',
),
3 => 
array (
    'email' => 'qux@email.com',
    'name' => 'qux',
),
)

如果要添加多个元素,这是一个有用的功能。

然而,只是附加到数组更容易:

$items[] = $item;

或者简单地说:

$items[3] = $item;