Here is my PHP code:
<?php
session_start();
include"smsciniz/vendor/autoload.php";
include"smsciniz/baglan.php";
//$insert = $DB->query("INSERT INTO sc_ulke(ulke_isim) VALUES(?)", array($_POST["ulke_isim"]));
$ulke = $DB->query("SELECT * FROM sc_ulke");
foreach ($ulke as $value) {
$url = file_get_contents("https://5sim.net/v1/guest/products/".trim($value["ulke_isim"])."/any");
$json = json_decode($url,true);
echo $json;
}
?>
And here is my JSON data:
"1688": {
"Category": "activation",
"Qty": 2000,
"Price": 14.83
},
"1xbet": {
"Category": "activation",
"Qty": 11413,
"Price": 19
},
"32red": {
"Category": "activation",
"Qty": 4113,
"Price": 7
},
"888casino": {
"Category": "activation",
"Qty": 4109,
"Price": 5
},
"99app": {
"Category": "activation",
"Qty": 5437,
"Price": 5
},
I want to print the area I marked but I don't know how to do.
I would be very happy if you could help me with an example, thank you in advance
"32red": {
"Category": "activation",
"Qty": 4113,
"Price": 7
},
We can iterate and find by particular key and print result using json_encode with JSON_PRETTY_PRINT
function findObjByKey($res, $keyToFind){
foreach ($res as $key => $value) {
if($key == $keyToFind) {
return $value;
}
}
return NULL;
}
$json = json_decode('
{"1688": {
"Category": "activation",
"Qty": 2000,
"Price": 14.83
},
"1xbet": {
"Category": "activation",
"Qty": 11413,
"Price": 19
},
"32red": {
"Category": "activation",
"Qty": 4113,
"Price": 7
},
"888casino": {
"Category": "activation",
"Qty": 4109,
"Price": 5
},
"99app": {
"Category": "activation",
"Qty": 5437,
"Price": 5
}}'
);
$res = findObjByKey($json, '32red');
$prittyPrint= json_encode($res, JSON_PRETTY_PRINT);
echo "<pre>".$prittyPrint."<pre>";
use json_encode($json['32red']) like this you can access any key in json
Related
I'm retrieving data from a database and pushing it to arrays then use json_encode() to output in json format. I have ended up having the data in this format.
[
{
"category_id": "1",
"category_name": "Construction Materials"
},
{
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "700",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
Here is what I want to achieve:
[
{
"category_id": "1",
"category_name": "Construction Materials"
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "40",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
How can I achive this in php. Is it possible to edit the contents of the main array? how can I add "items" after "category_name"
Regards..
$array = json_decode($yourJson);
$arrayLength = count($array);
$finalArray = [];
for ($i=0; $i < $arrayLength; $i+=2) {
$finalArray[] = $array[$i] + $array[$i + 1];
}
$backToJson = json_encode($finalArray);
Alternative to Mattijs's answer.
function get_first_property($object) {
$properties = array_keys(get_object_vars($object));
return reset($properties);
}
function object_merge($object1, $object2) {
return (object) array_merge((array) $object1, (array) $object2);
}
// loop through each of the array objects
$previous_first_property = null;
foreach ($array as $i => $object) {
$first_property = get_first_property($object);
// merge if the 1st property is "items", and the previous 1st was "category_id"
if ($first_property == "items" && $previous_first_property == "category_id") {
$array[$i - 1] = object_merge($array[$i - 1], $array[$i]);
unset($array[$i]);
}
$previous_first_property = $first_property;
}
What i'm trying to do is get the each array key and then associate the first "price" and "quantity" with each array key.
My array:
{
"32557580": {
"bids": [
{
"price": 2500,
"quantity": 38265661
},
{
"price": 2439,
"quantity": 57414444
},
{
"price": 2381,
"quantity": 1092179
},
{
"price": 2174,
"quantity": 27140648
}
],
"offers": [
{
"price": 2564,
"quantity": 33634591
},
{
"price": 2597,
"quantity": 27842125
},
{
"price": 2632,
"quantity": 925092
},
{
"price": 2667,
"quantity": 3565173
},
{
"price": 2778,
"quantity": 27589980
}
]
},
"32557581": {
"bids": [
{
"price": 4854,
"quantity": 33786947
},
{
"price": 4808,
"quantity": 22881344
},
{
"price": 4762,
"quantity": 2513747
},
{
"price": 4717,
"quantity": 2650000
},
{
"price": 4587,
"quantity": 15714786
}
],
"offers": [
{
"price": 4950,
"quantity": 31749492
},
{
"price": 5000,
"quantity": 3193999
},
{
"price": 5051,
"quantity": 2292463
},
{
"price": 5102,
"quantity": 34770816
},
{
"price": 5128,
"quantity": 2605693
}
]
},
"32557582": {
"bids": [
{
"price": 2532,
"quantity": 60354703
},
{
"price": 2500,
"quantity": 113667648
},
{
"price": 2439,
"quantity": 5125100
},
{
"price": 2222,
"quantity": 120803051
}
],
"offers": [
{
"price": 2564,
"quantity": 1492990
},
{
"price": 2597,
"quantity": 22121811
},
{
"price": 2632,
"quantity": 42119270
},
{
"price": 2667,
"quantity": 43680406
},
{
"price": 2703,
"quantity": 1176966
}
]
}
}
Example:
Id: 32557580
Price: 2500
Quantity: 38265661
Id: 32557581
Price: 4854
Quantity: 33786947
etc..
This is what i got so far
$obj = json_decode($result,true);
$all_keys = array_keys($obj);
foreach ($all_keys as $key => $value) {
echo 'Id: '.$value.'<br>';
}
Output from this is:
Id: 32557580
Id: 32557581
Id: 32557582
I'm not really sure where to go from here, i have tried look at multiple questions and answers elswere.
I tried adding another foreach inside the one i got but i only got the price and quantity from the first array key.
All help with getting me on the right track is appreciated.
Just loop the main array and get the first from bids and use that:
foreach($obj as $key => $value) {
$first = reset($value['bids']);
echo "ID: $key<br />";
echo "Price: " . $first['price'] . "<br />";
echo "Quantity: " . $first['quantity'] . "<br />";
}
Or use the index, which in this case is 0 but may not always be depending on the JSON:
foreach($obj as $key => $value) {
echo "ID: $key<br />";
echo "Price: " . $value['bids'][0]['price'] . "<br />";
echo "Quantity: " . $value['bids'][0]['quantity'] . "<br />";
}
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'] ;
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"
}]
}
}
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"
}
]
}
]
}