In PHP, how can I make this data:
{
"items": {
"item": [{
"id": "59",
"type": "Domain",
"relid": "27",
"description": "Sample Monthly Product(01\ / 01\ / 2016 - 31\ / 01\ / 2016)",
"amount": "180.00",
"taxed": "0"
}]
}
}
Have this format:
{
"items[item][0][id]": "59",
"items[item][0][type]": "Domain",
"items[item][0][relid]": "27",
"items[item][0][description]": "Sample Monthly Product (01\/01\/2016 - 31\/01\/2016)",
"items[item][0][amount]": "180.00",
"items[item][0][taxed]": "0"
}
Reason: Setting up a Zap (via Zapier) using email parser to import invoices from WHMCS, and it seems to work with parsing data when 2nd format (items[item][0][id]) to read the line descriptions but not when using the 1st. In the WHMCS API ref it shows it outputting as the 2nd format but can't see why mine looks like 1st (developers.whmcs.com/api-reference/getinvoice)
I think this might work with your current setup:
<?php
//assuming your current dataset isn't in JSON, you can ignore this part
$json = '{
"items": {
"item": [{
"id": "59",
"type": "Domain",
"relid": "27",
"description": "Sample Monthly Product",
"amount": "180.00",
"taxed": "0"
},
{
"id": "203",
"type": "Server",
"relid": "86",
"description": "Sample Yearly Product",
"amount": "290.00",
"taxed": "1"
}]
}
}';
$json = json_decode($json, true);
$parsed = array();
foreach ($json['items']['item'] as $index => $item)
foreach ($item as $attr => $val)
$parsed['items[item][' . $index . '][' . $attr . ']'] = $val;
echo json_encode($parsed);
Output:
{
"items[item][0][id]": "59",
"items[item][0][type]": "Domain",
"items[item][0][relid]": "27",
"items[item][0][description]": "Sample Monthly Product",
"items[item][0][amount]": "180.00",
"items[item][0][taxed]": "0",
"items[item][1][id]": "203",
"items[item][1][type]": "Server",
"items[item][1][relid]": "86",
"items[item][1][description]": "Sample Yearly Product",
"items[item][1][amount]": "290.00",
"items[item][1][taxed]": "1"
}
Related
I wonder how can I unset the target array whenever i wanted in PHP. It's a product list and the procedure im planning if i want to delete a products. Here's the JSON structure
{
"Merchant": "SAMHONEY",
"date": 1632482493,
"archive": "true",
"extra": "Byahe",
"data": [
{
"product-image": "https:\/\/mobi.asia\/assets\/abunjing-stand.png",
"name": "Sample Product",
"des": "Byahe Palawan Merchant Dashboard v.1.1",
"price": "26"
},
{
"product-image": "https:\/\/mob.asia\/assets\/abunjing-stand.png",
"name": "Sample Product 2",
"des": "Byahe Palawan Merchant Dashboard v.1.1",
"price": "99"
},
{
"product-image": "https:\/\/mob.asia\/01162020\/images\/storage\/1632200295.png",
"name": "Product C",
"des": "Great coffee",
"price": "3"
},
{
"product-image": "https:\/\/mob.asia\/01162020\/images\/storage\/1632200342.png",
"name": "Product A",
"des": "Caramel Coffee",
"price": "4"
}
]
}
What I done in PHP is this
$pos = $_POST['position'];
$jsn = file_get_contents('../datamer/archives/'.$sbd.".json");
$arr = json_decode($jsn, true);
$acc = $arr["data"];
unset($acc[$pos]);
$arr["data"] =$acc;
file_put_contents('../datamer/archives/'.$sbd.".json",json_encode($arr,JSON_PRETTY_PRINT));
And the output is it was re-structuring the JSON into this.Which not im expecting
{
"Merchant": "SAMHONEY",
"date": 1632482493,
"archive": "true",
"extra": "Byahe",
"data": {
"0": {
"product-image": "https:\/\/mobile.byahe.asia\/assets\/abunjing-stand.png",
"name": "Sample Product",
"des": "Byahe Palawan Merchant Dashboard v.1.1",
"price": "26"
},
"2": {
"product-image": "https:\/\/mobile.byahe.asia\/01162020\/images\/storage\/1632200295.png",
"name": "Product C",
"des": "Great coffee",
"price": "3"
},
"3": {
"product-image": "https:\/\/mobile.byahe.asia\/01162020\/images\/storage\/1632200342.png",
"name": "Product A",
"des": "Caramel Coffee",
"price": "4"
}
}
}
Kindly enlighten me to this. I'm still learning,. Thanks in advance for the attention. Well appreciated.
I'm trying to update a json file and I'm using laravel command to do it. In that file there are specific product codes that need to be changed. The code I'm doing to do this isn't working, it runs but nothing changes.
Here is my code
$old_code = 'P001';
$new_code = 'P011';
$productJson = json_decode(file_get_contents(storage_path('/Product 1/product.json')));
foreach($productJson as $key => $value){
str_replace($old_code, $new_code, $k);
}
file_put_contents(storage_path('/Product 1/product.json), json_encode($productJson, JSON_PRETTY_PRINT));
and this is my json file
{
"P001": {
"name": "Product 1",
"price": "200",
"category": "Shirts"
},
"P002": {
"name": "Product Test",
"price": "100",
"category": "Tops"
},
}
Its probably simpler to read the file and create a new JSON with the new codes like this
$s = '{"P001": {
"name": "Product 1",
"price": "200",
"category": "Shirts"
},
"P002": {
"name": "Product Test",
"price": "100",
"category": "Tops"
},
"P003": {
"name": "Product Test",
"price": "50",
"category": "Bottoms"
}
}';
$old_codes = ['P001', 'P002' ];
$new_codes = ['P011', 'P022' ];
$productJson = json_decode($s);
$new = new stdClass;
foreach($productJson as $key => $json){
$kk = array_search($key, $old_codes);
if ( FALSE !== $kk ) { // found
$new->{$new_codes[$kk]} = $json;
} else {
$new->{$key} = $json;
}
}
echo json_encode($new, JSON_PRETTY_PRINT);
//file_put_contents(storage_path('/Product 1/product.json'), json_encode($new, JSON_PRETTY_PRINT));
RESULT
{
"P011": {
"name": "Product 1",
"price": "200",
"category": "Shirts"
},
"P022": {
"name": "Product Test",
"price": "100",
"category": "Tops"
},
"P003": {
"name": "Product Test",
"price": "50",
"category": "Bottoms"
}
}
I'm trying to get data from API and I receive this
[
{
"service": 1,
"name": "Followers",
"type": "Default",
"category": "First Category",
"rate": "0.90",
"min": "50",
"max": "10000"
},
{
"service": 2,
"name": "Comments",
"type": "Custom Comments",
"category": "Second Category",
"rate": "8",
"min": "10",
"max": "1500"
}
]
I want to get the category for each service without repeating the same category twice.
Edited*
I have this code
$servers = $this->Setting->Loop('api','WHERE is_active = 1');
foreach($servers->result() as $server){
foreach($this->Api_Connect->services($server->api_url, $server->api_key) as $item) {
echo '<option data-server='.$server->id.' data-percent='.$server->addon_percent.' data-price='.$item['rate'].' data-min='.$item['min'].' data-max='.$item['max'].' value="'.$item['service'].'">- '.$item['name'].'</option>';
}
}
which connect to each server with api url and key and return with the services.
We can set a new array, and push categories in the new array, and check if the new value does not exist do so:
$data = '[
{
"service": 1,
"name": "Followers",
"type": "Default",
"category": "First Category",
"rate": "0.90",
"min": "50",
"max": "10000"
},
{
"service": 2,
"name": "Comments",
"type": "Custom Comments",
"category": "Second Category",
"rate": "8",
"min": "10",
"max": "1500"
},
{
"service": 2,
"name": "Comments",
"type": "Custom Comments",
"category": "Second Category",
"rate": "8",
"min": "10",
"max": "1500"
}
]';
$data = json_decode($data, true);
$category = array();
foreach ($data as $value) {
if (!array_search($value["category"], $category)) {
array_push($category, $value["category"]);
}
}
var_dump($category);
Output
array(2) {
[0]=>
string(14) "First Category"
[1]=>
string(15) "Second Category"
}
Edit:
Based on Andreas's advice, we can also use if(in_array()) in the loop using:
$category[$value["category"]] = $value["category"];
which is much more efficient.
$array = [];
foreach($object as $key => $value) {
// object is data you receive from API
array_push($array,$value->category);
}
// to get unique values
$array = array_unique($array);
I hope this code solve your problem
The fastest method is to use array_column.
Array_column will isolate one column of the array.
The third parameter of array_column will set the key name.
This is what we want.
Because you don't want duplicates we set something as value and "category" as key.
This means it will loop once and overwrite the keys that is duplicated.
The other methods posted here will need to check if the item is already added to the list or using array_unique which needs to compare each item with every other item, that is a slow function when you give it a large array.
$data = '[
{
"service": 1,
"name": "Followers",
"type": "Default",
"category": "First Category",
"rate": "0.90",
"min": "50",
"max": "10000"
},
{
"service": 2,
"name": "Comments",
"type": "Custom Comments",
"category": "Second Category",
"rate": "8",
"min": "10",
"max": "1500"
},
{
"service": 2,
"name": "Comments",
"type": "Custom Comments",
"category": "Second Category",
"rate": "8",
"min": "10",
"max": "1500"
}
]';
$data = json_decode($data, true);
$category = array_column($data, "rate", "category");
var_dump($category);
Output of this:
// Note it's only the keys we want, the values are not interesting
array(2) {
["First Category"]=>
string(4) "0.90"
["Second Category"]=>
string(1) "8"
}
$jsonResponse='[
{
"service": 1,
"name": "Followers",
"type": "Default",
"category": "First Category",
"rate": "0.90",
"min": "50",
"max": "10000"
},
{
"service": 2,
"name": "Comments",
"type": "Custom Comments",
"category": "Second Category",
"rate": "8",
"min": "10",
"max": "1500"
}
]';
$listData=json_decode(jsonResponse,true);
foreach($listData as $valRes){
echo $valRes['category'];
}
you can get category
I am trying to take my JSON input and generate a easy array to search in, but it is as far as I can tell giving me some trouble.
First of, this is my JSON as is, loaded from a file:
{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}
Is there a way to simplify this or minimise the number of arrays?
I have been using the following code to preview my array, but I am trying to get it to search for id and then print the values for id, boat and name.
$json_url = "teams.json";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo '<pre>';
print_r($data);
echo '</pre>';
This is really quite simple. There is no need to convert a perfectly good object into an array, it only makes life more complex.
The only array you have in your data structure is the teams array and that is easily processed like this
$json = '{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}';
$data = json_decode($json);
//print_r($data);
foreach ($data->teams as $object) {
if ( $object->id == 2) {
echo 'boat is ' . $object->boat . ' and name is ' . $object->name . PHP_EOL;
}
}
And the result of the above example would be
boat is Test 2 and name is Name Test 2
Below is json code where i have o display its values. How to fetch the output as given below
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
Output should come like this
Name : Le Grand Bouquet Blanc, Price : 65
Name : Roses, Price : 33
Name : Mandarine, Price : 125
Total: 223 Euro
Any Help?
JSON decode, loop through the data and output the required text like so:
$data = json_decode($jsondata);
$total = 0;
foreach($data->flowers as &$datum) {
printf('Name : %s, Price: %d'.PHP_EOL, $datum->name, $datum->price);
$total += $datum->price;
}
printf('Total: %d Euro'.PHP_EOL, $total);
Read up on some basic PHP functions/concepts:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.printf.php
http://php.net/manual/en/function.echo.php
http://php.net/manual/en/language.operators.arithmetic.php
Try using json_decode() with true as second attribute to convert JSON it into array first.Then use foreach loop and get desired result.
<?php
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$array = json_decode($jsondata,true);
//print_r($array);
$sum = 0;
foreach($array['flowers'] as $flowers)
{
echo "Name : ".$flowers['name'].",Price : ".$flowers['price'].PHP_EOL;
$sum+=$flowers['price'];
$currency = $flowers['currency'];
}
echo "Total:".$sum." ".$currency;
Try this.
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$data = json_decode($jsondata,true);
echo "Name : " . $data['flowers'][0]['name'] . ' , Price: ' . $data['flowers'][0]['price'] ;