首页 > 解决方案 > 将数组添加到现有数组...在另一个数组中?

问题描述

我有以下数组,其中填充了数据库值(此示例中的“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']
);

标签: phparrays

解决方案


您可以简单地将其推送到您的 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


推荐阅读