Re: Stripping a JSON of extra characters in PHP
Arno Welzel <[email protected]> Tue, 7 Feb 2023 09:31:14 +0100
| Newsgroups | comp.lang.php |
|---|---|
| Message-ID | <[email protected]> |
Arno Welzel, 2023-02-07 09:16:
> The Doctor, 2023-02-07 02:28:
>
> [...]
>> cart is subarray with the main array, added items in the cart
>> is a subarray of the cart.>
>> Source
>>
>> https://developer.moneris.com/livedemo/checkout/preload_req/guide/dotnet
>
> No! Cart is an OBJECT there:
>
> "cart":{
> ...
> }
>
> Also contact details:
>
> "contact_details":{
> ...
> }
>
> The "{" indicates the beginning of an OBJECT while "[" starts an ARRAY.
>
> As I said: learn how to read JSON and try to understand how that format
> works!
>
> Also see: <https://www.json.org/json-en.html>
In addition:
To create an OBJECT in PHP use something like this - as a reduced example:
<?php
class CartItem
{
public $url;
public $description;
public $product_code;
public $unit_cost;
public $quantity;
}
class TaxItem
{
public $amount;
public $description;
public $rate;
}
class Cart
{
public $items;
public $subtotal;
public $tax;
};
$cart = new Cart();
$cartItem = new CartItem();
$cartItem->url = "https:\/\/example.com\/examples\/item1.jpg";
$cartItem->description = "One item";
$cartItem->product_code = "one_item";
$cartItem->unit_cost = "100.00";
$cartItem->quantity = "1";
$cart->items[] = $cartItem;
$cartItem = new CartItem();
$cartItem->url = "https:\/\/example.com\/examples\/item2.jpg";
$cartItem->description = "Two item";
$cartItem->product_code = "two_item";
$cartItem->unit_cost = "200.00";
$cartItem->quantity = "1";
$cart->items[] = $cartItem;
$cartItem = new CartItem();
$cartItem->url = "https:\/\/example.com\/examples\/item3.jpg";
$cartItem->description = "Three item";
$cartItem->product_code = "three_item";
$cartItem->unit_cost = "100.00";
$cartItem->quantity = "1";
$cart->items[] = $cartItem;
$cart->subtotal = "400.00";
$taxItem = new TaxItem();
$taxItem->amount = "52.00";
$taxItem->description = "Taxes";
$taxItem->rate = "13.00";
$cart->tax = $taxItem;
echo json_encode($cart, JSON_PRETTY_PRINT);
?>
Result of this as formatted output:
{
"items": [
{
"url": "https:\\\/\\\/example.com\\\/examples\\\/item1.jpg",
"description": "One item",
"product_code": "one_item",
"unit_cost": "100.00",
"quantity": "1"
},
{
"url": "https:\\\/\\\/example.com\\\/examples\\\/item2.jpg",
"description": "Two item",
"product_code": "two_item",
"unit_cost": "200.00",
"quantity": "1"
},
{
"url": "https:\\\/\\\/example.com\\\/examples\\\/item3.jpg",
"description": "Three item",
"product_code": "three_item",
"unit_cost": "100.00",
"quantity": "1"
}
],
"subtotal": "400.00",
"tax": {
"amount": "52.00",
"description": "Taxes",
"rate": "13.00"
}
}
Hopefully you understand the idea now - if you don't want an ARRAY in
the JSON then do not create one! If the specification asks for an OBJECT
then use an OBJECT based on a class with named members.
--
Arno Welzel
https://arnowelzel.de