如何创建动态数组?

时间:2021-01-19 10:10:43

标签: php arrays

如何创建动态数组?我需要设置产品id和qty的动态值并传入items数组。

$itemarray = [];
foreach ($ItemCollection as $item) {
    $productId = $item['order_item_id'];
    $qty = $item['qty'];
}  
        $orderData = [
            'email'        => $customerEmail, //buyer email id
            'shipping_address' => [
            'firstname'    => $firstname, //address Details
            'lastname'     => $lastname,
            'street' => $address,
            'city' => $city,
            'country_id' => $countryid,
            'region' => $region,
            'regionId' => $regionid,
            'postcode' => $postcode,
            'telephone' => $telephone
        ],
        'items'=> [ 
            //array of product which order you want to create
            ['product_id'=>'1','qty'=>1],
            ['product_id'=>'2','qty'=>2]
         ]
        ]
        ;

2 个答案:

答案 0 :(得分:2)

我想是这样的:

$orderData = [
    'email'        => $customerEmail, //buyer email id
    'shipping_address' => [
        'firstname'    => $firstname, //address Details
        'lastname'     => $lastname,
        'street' => $address,
        'city' => $city,
        'country_id' => $countryid,
        'region' => $region,
        'regionId' => $regionid,
        'postcode' => $postcode,
        'telephone' => $telephone
    ],
    'items'=> []
];
foreach ($ItemCollection as $item) {
    // append data to 'items' subarray
    $orderData['items'][] = [
        'product_id' => $item['order_item_id'],
        'qty' => $item['qty'],
    ];
} 

答案 1 :(得分:2)

首先构造您的基本 $orderData 数组并将“items”初始化为 $orderData 中的一个空数组。之后,您可以构建您的项目并将它们推送到 $orderData['items']:

<?php
$orderData = [
    'email' => $customerEmail, //buyer email id
    'shipping_address' => [
        'firstname' => $firstname, //address Details
        'lastname' => $lastname,
        'street' => $address,
        'city' => $city,
        'country_id' => $countryid,
        'region' => $region,
        'regionId' => $regionid,
        'postcode' => $postcode,
        'telephone' => $telephone
    ],
    'items' => [] // Initialize as empty array
];

foreach ($ItemCollection as $item) {
    // Build order item data
    $orderItem = [
        'product_id' => $item['order_item_id'],
        'qty' => $item['qty']
    ];

    $orderData['items'][] = $orderItem; // Push into items array of order data array
}