将数组添加到现有数组...在另一个数组中?

时间:2018-05-15 14:56:51

标签: php arrays

我有以下数组,其中填充了数据库值(本例中的' PickItems'除外):

$params = array(
    'DeliveryCompanyName' => $row['company_name'],
    'DeliveryAddress1' => $row['address1'],
    'DeliveryAddress2' => $row['address2'],
    'DeliveryCity' => $row['city'],
    'DeliveryCounty' => $row['province'],
    'DeliveryPostCode' => $row['postcode'],
    'DeliveryCountry' => $row['country'],
    'DeliveryPhone' => $row['phone'],
    'DeliveryContact' => $row['first_name'] . " " . $row['last_name'],
    'OutboundRef' => $row['order_number'],
    'PickItems' => array(
        array(
            'SKUNumber' => 'SKU',
            'Quantity' => '1',
            'Comments' => 'Comments'
        )
    ),
    'BranchID' => '',
    'CustRef' => $row['order_number']
);

在这个数组中,是一个名为" PickItems"它包含一系列数组,每个数组都是单独的产品。

我正试图在另一个数据库查询中使用while循环来填充这些" PickItems"。

这是我开始编写的代码,以便遍历包含订单的各个项目的数据库,我需要将这些代码放入数组并将该数组放入主数组中。我正在努力的部分是将这些值和键放入数组中,我认为array_push是要走的路,但另一个问题的另一个答案是你不能这样做。

if ($result2 = $mysqli->query("SELECT * FROM order_items WHERE client_id = {$client} AND main_order_id = {$row['platform_order_id']}")) {

    $Items = array();

    while($row2 = mysqli_fetch_assoc($result2)) {
        //Add the following values to the items array
        //'SKUNumber' => $row2['sku'],
        //'Quantity' => $row2['quantity'],
        //'Comments' => $row2['comments']
    }
}

我怀疑主阵列需要更改为这样的东西? :

$params = array(
    'DeliveryCompanyName' => $row['company_name'],
    'DeliveryAddress1' => $row['address1'],
    'DeliveryAddress2' => $row['address2'],
    'DeliveryCity' => $row['city'],
    'DeliveryCounty' => $row['province'],
    'DeliveryPostCode' => $row['postcode'],
    'DeliveryCountry' => $row['country'],
    'DeliveryPhone' => $row['phone'],
    'DeliveryContact' => $row['first_name'] . " " . $row['last_name'],
    'OutboundRef' => $row['order_number'],
    'PickItems' => array($Items),
    'BranchID' => '',
    'CustRef' => $row['order_number']
);

2 个答案:

答案 0 :(得分:2)

你可以在while循环中简单地推送它:

array_push($params['PickItems'], array(
    'SKUNumber' => $row2['sku'],
    'Quantity' => $row2['quantity'],
    'Comments' => $row2['comments']
));

输出

'PickItems' => array(
    array(
        'SKUNumber' => 'SKU',
        'Quantity' => '1',
        'Comments' => 'Comments'
    ),
    array(
        'SKUNumber' => 'SKU 2', // Value from $row2['sku']
        'Quantity' => '2', // Value from $row2['quantity']
        'Comments' => 'Comments2' // Value from $row2['comments']
    ),
),

有关详细信息:http://php.net/manual/en/function.array-push.php

答案 1 :(得分:-1)

要添加到数组,在数组中,只需执行此操作!

对于关联键值数组:

$params['PickItems']['whatever'] = $row2;

或者对于数字数组:

$params['PickItems'][] = $row2;