Display value of json to output - php

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'] ;

Related

Changing a string in a json object

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"
}
}

php foreach nested loop retrieve all records

$json_string = '{
"response_code": 200,
"info": {
"days": [
{
"code": "A",
"runs": "111"
},
{
"code": "B",
"runs": "222"
},
{
"code": "C",
"runs": "333"
}
],
"name": "SUPER MARIO",
"number": "010203",
"classes": [
{
"points": "6523",
"name": "ABC",
"available": "N"
},
{
"points": "4253",
"name": "XYZ",
"available": "N"
},
{
"points": "2323",
"name": "JOHN",
"available": "N"
},
{
"points": "5236",
"name": "TAMIL",
"available": "N"
}
]
}
}';
$jsondata = $json_string;
$arr = json_decode($jsondata, true);
foreach($arr as $k=>$v)
{
echo $k."<br>";
}
it prints
response_code
info
But, I need the results like this
6523 ABC
4253 XYZ
2323 JOHN
5326 TAMIL
I have tried and achieved this above results using this below code. But, I want to do it using foreach loop. How do list out all information using foreach?
echo "".$arr['info']['classes'][0]['points']." ".$arr['info']['classes'][0]['name']."<br/>";
echo "".$arr['info']['classes'][1]['points']." ".$arr['info']['classes'][1]['name']."<br/>";
echo "".$arr['info']['classes'][2]['points']." ".$arr['info']['classes'][2]['name']."<br/>";
echo "".$arr['info']['classes'][3]['points']." ".$arr['info']['classes'][3]['name']."<br/>";
You should foreach your array key
foreach($arr['info']['classes'] as $k=>$v)
{
echo $v['points']." " . $v['name']."<br>";
}

Displaying key/value in PHP object

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"
}

Display some parts of a file written in json

Below is my JSON file:
{
"example": "1",
"example2": 2,
"text": "3",
"info": {
"agent": 4,
"sum": 5,
"collection": [{
"Name": "6",
"Pic": "7"
} {
"Name": "8",
"Pic": "9"
}, {
"Name": "10",
"Pic": "11"
}]
}
}
How would I display each 'name' and 'pic' I think I need to use a foreach loop but don't know how to.
This is all the code I have:
$data = json_decode(file_get_contents('http://linktojson.com'));
echo $data['info']['collection'][0]['Name'];
echo $data['info']['collection'][0]['Pic'];
This should work
$data = json_decode(file_get_contents('http://linktojson.com'));
echo "<pre>".print_r($data,1)."</pre>";
foreach($data->info->collection as $key){
echo $key->Pic;
echo $key->Name;
}
Valid JSON
{
"example": "1",
"example2": 2,
"text": "3",
"info": {
"agent": 4,
"sum": 5,
"collection": [{
"Name": "6",
"Pic": "7"
}, {
"Name": "8",
"Pic": "9"
}, {
"Name": "10",
"Pic": "11"
}]
}
}

remove unnecessary hierarchy from json output

I am building an admin backend for an android app. My code provides a json output which the android developer then uses in his app. The developer asked me if it is possible to reduce the hierarchy level in the json output
as in remove the highlighted []0 and put the contents directly inside the []data instead.
This is my current php code
if($type == 1 ) //Handle item display
{
try
{
$query = "SELECT category FROM category";
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($row1 = $value->fetchAll(PDO::FETCH_OBJ)){
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
$result->closeCursor(); //Close database connection free resources
$DBH = null;
}
catch(PDOException $e){
print $e->getMessage ();
die();
}
}
And the json output being generated
[
{
"data": [
[
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
]
},
{
"data": {
"catagory": "Dinner"
}
},
{
"data": {
"catagory": "Soup"
}
},
{
"data": {
"catagory": "Test"
}
}
]
I am not very sure if I can make the changes he asked or if it is possible. Is it doable?
Your json structure is inconsistent and try this approach, will be easier for the developer to parse
{
"response": [
{
"data": [
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
},
{
"data": [
{
"catagory": "Dinner"
}
]
},
{
"data": [
{
"catagory": "Soup"
}
]
},
{
"data": [
{
"catagory": "Test"
}
]
}
]
}

Categories