Fetch json data using PHP - php

I have a json file and I want to display it data using PHP. My below code gives me error,
$json = file_get_contents('data.json');
$data = json_decode($json,true);
$users = $data['devices'];
foreach($users as $user)
{
echo $user['id'];
echo $user['user'];
}
When I replace the 3rd LOC with $users = $data['user']; then it display some data with single alphabet i don't know in which order.
Data.json file contains the following data
{
"user":
{
"id":"#03B7F72C1A522631",
"user":"test#mail.com",
"password":"123",
"email":"test#mail.com",
"name":"m",
"creationDate":1385048478,
"compression":true,
"imageProfile":"medium",
"videoProfile":"medium",
"blockAdvert":true,
"blockTracking":true,
"devices":[
{
"id":"#13C73379A7CC2310",
"udid":"cGMtd2luNi4xLV",
"user":"test#mail.com",
"creationDate":1385048478,
"status":"active",
},
{
"id":"#FE729556EDD9910D",
"udid":"C1N1",
"user":"test#mail.com",
"creationDate":1385291938,
"status":"active",
}]
},
"status":
{
"version":"0.9.5.0",
"command":"getuser",
"opf":"json",
"error":false,
"code":0
}
}

I believe you skipped 1 node, try:
$users = $data['user']['devices'];

This should work;
$json = file_get_contents('data.json');
$data = json_decode($json,true);
$users = $data['user']['devices'];
foreach($users as $user) {
echo $user['id'];
echo $user['user'];
}
There is one key before 'devices'.

I think you may want do display all the devices info, you can change you code to:
$json = file_get_contents('data.json');
$data = json_decode($json,true);
// change the variable name to devices which is clearer.
$devices = $data['user']['devices'];
foreach ($devices as $device)
{
echo $device['id'];
echo $device['user'];
}

You are not accessing your json correctly. You need to access it like this.
$yourVariable = $data['users']['devices'];
Try that.

Related

Get data from json file without index in php

I have a JSON file like this
[
{
"item_id": "342",
"item_title": "James"
},
{
"item_id": "374",
"item_title": "Fred"
}
]
And I would like to get the item_title in PHP but using the item_id.
How would I go about this?
I have
$item_id = 374;
$url = 'file.json';
$data = file_get_contents($url);
$items = json_decode($data);
Thank you.
You can use array_search() and array_column() if you know that key will always exist
echo $items[array_search($item_id,array_column($items,'item_id'))]['item_title'];
https://3v4l.org/Qddcj
Otherwise go for functional approach
$items = json_decode($data,true);
function getItemTitle($array,$item_id){
$key = array_search($item_id,array_column($array,'item_id'));
if($key !==false && isset($array[$key]['item_title'])){
return $array[$key]['item_title'];
}else{
return "no title found for given id ".$item_id;
}
}
echo getItemTitle($items,$item_id);
Output:- https://3v4l.org/ikKWY
In case if same id can be repeated multiple time
$items = json_decode($json,true);
foreach($items as $value){
if($value['item_id']==$item_id){
echo $value['item_title'].PHP_EOL;
}
}
Output:- https://3v4l.org/7oPHk
Some explanation: you should use foreach loop with if condition
Here is the sample code
<?php
$json='[
{
"item_id": "342",
"item_title": "James"
},
{
"item_id": "374",
"item_title": "Fred"
}
]';
$item_id = 374;
$items = json_decode($json);
//print_r($items);
foreach($items as $value){
if($value->item_id==$item_id){
echo $value->item_title;
}
}
You can check the desired output here

how to read from json array in codeingiter

Im trying to decode json and get value from the json code.
[{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":1,
"menu_category_id":1,
"status":0
} ,
{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":2,
"menu_category_id":1,
"status":0
}]
i need to read from this json and create an array with add_food_item_a and status.
currently I'm using like this
public function readJson()
{
$json_obj = json_decode('');
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]) && !empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
$json_text = $this->cleanMe($GLOBALS["HTTP_RAW_POST_DATA"]);
// now insert into user table
$json_obj = json_decode($json_text);
}
return $json_obj;
}
and I call this function like
$add_food_item_a = isset($json_obj->add_food_item_a) ? $json_obj->add_food_item_a : '';
but can't read from this array of json code
Are you trying to fetch the value of 'add_food_item_a' and 'status'
<?php
$json='[{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":1,
"menu_category_id":1,
"status":0
} ,
{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":2,
"menu_category_id":1,
"status":0
}]';
echo "<pre>";
$array = json_decode($json,1);
print_r($array);
foreach($array as $value)
{
echo "\n".$value['add_food_item_a'];
echo "\n".$value['status'];
}

How to get the values from JSON Array Stored as Value in JSON using PHP?

`{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}`
I am trying to get the value of rno using PHP code
`$data = json_decode($json, true);
foreach ($data as $item) {
$name = $item['name'] ;
$number= $item['rno'] ;
}`
#Sahil Gulati's code is more prefect and right way to parse the json in php
here is an other way to parse the json data in php
<?php
$data = json_decode($json, true);
foreach ($data as $item) {
foreach ($item as $val) {
echo $name = $val['name'];
echo $number = $val['rno'];
}
}
?>
the above code that i have shared you can understand easily. but after learning that how to parse json data in php you should use #Sahil Gulati's mathod.
Change this to:
foreach ($data as $item)
This:
foreach ($data["student"] as $item)
Try code snippet here
PHP code:
<?php
ini_set('display_errors', 1);
$data = json_decode($json, true);
foreach ($data["student"] as $item)
{
$name = $item['name'];
$number = $item['rno'];
}
You should take a closer look at the structure of the json encoded data. That helps to implement a clean iteration:
<?php
$input = <<<JSON
{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}
JSON;
$data = json_decode($input);
$output = [];
array_walk($data->student, function($entry) use (&$output) {
$output[] = $entry->rno;
});
print_r($output);
The output of above code obviously is:
Array
(
[0] => 187654
)
The output format has been chosen as an array, since the json structure suggests that multiple students can be contained.
If you are only directly interested in the rno property of the first entry in the student array, then you can access it directly:
<?php
$input = <<<JSON
{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}
JSON;
$data = json_decode($input);
var_dump($data->student[0]->rno);
The output of that variant obviously is:
string(6) "187654"

Overwrite a json after modification in PHP

I make a modification in my json with this code:
$id = "hotel_name";
$value ="My Hotel";
$json = json_decode(file_get_contents('datas.json'));
$datas = $json->datas;
foreach ($datas as $category => $data) {
foreach ($data as $element) {
if($element->id==$id) {
$datas->$category->$element->$id = $value;
}
}
}
$newJson = json_encode($element);
file_put_contents('datas.json', $newJson);
But it do not put all the content in it.
How to solve it please ?
My json has the following:
{
"datas": {
"General": [
{
"field": "hotel_name",
"name": "My Hotel name"
}
]
}
}
You are accessing the $element variable, which contains only your inner most data
{
"field": "hotel_name",
"name": "My Hotel name"
}
If you want more of your data, you will have to reassign your outermost $datas variable and children with the newly updated $element variable. I'd recommend creating an empty variable to store the new data instead of altering the original copy.
You should be encoding datas, not just the last element, right?
// before
$newJson = json_encode($element);
// after
$newJson = json_encode($datas);
By the way, you might find it easier to work with the data if you convert it to an array rather than object.
$json = json_decode(file_get_contents('datas.json'), true);

Count how many of the same element in json

Im parsing json with php in this simple piece of code
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
foreach($records as $record)
{
echo $record['number']." ".$record['opened_at'];
}
?>
But i want to echo how many 'number' element are in my json file exemple bellow
{
"records":[
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
$numberCount = 0;
foreach($records as $record)
{
$numberCount += isset($record['number']); // Here we go
echo $record['number']." ".$record['opened_at'];
}
echo $numberCount;
?>
This function might be helpful: http://www.php.net/manual/en/function.array-count-values.php
$counts = array_count_values($records);
$numberCount = $counts['number'];

Categories