简体   繁体   中英

PHP - foreach loop in array for generating a json file

Sorry, but I'm quite new to this.

I would like to achieve the following JSON code:

"commodities": [
    {
        "originCountryCode": "NL",
        "goodsDescription": "Commodity goods description ",
        "goodsValue": {
            "currencyCode": "EUR",
            "monetaryValue": 250
        }
    }

How can I make goodsValue a part of commodities? I've tried the following but I can't get it done.

$commodities = array();
$commoditie = array();
$goodsValue = array();
$commoditie["originCountryCode"] = "NL";
$commoditie["goodsDescription"] = "Electronics, ".$producten."";
array_push($commodities, $commoditie);
$goodsValue["currencyCode"] = "EUR";
$goodsValue["monetaryValue"] = "".$subtotaal."";
array_push($commodities, $goodsValue);
$data["commodities"] = $commodities;

How can I make 3 arrays into one and get "packages" into an object?

<?php
$response = array(); 
$response["code"] = 200;
$packages = array();

for ($i=0; $i < 3; $i++) { 
  $package = array(); 
  $package["grossWeight"] = $i;
  $package["scannedBy"] = "someone";
  array_push($packages, $package); // push it to packages array
}
$response["packages"] = $packages; // packages
echo json_encode($response);

Result will be

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM