PHP: How to get a value from a JSON file? - php

I'm using PHP and json_decode to use a remote API and I'm having what seems to be a newbie problem for which I didn't even know what to search to find my answer.
So on my script I have a $code = 392 and a json file which simplified version is:
{
"result": {
"items": [
{
"name": "New York",
"code": 7294,
},
{
"name": "Miami",
"code": 392,
},
{
"name": "Los Angeles",
"code": 9182,
}
]
}
}
So, simply put, having the code 392 I want to know which name corresponds to that code. How ?
(The actual json result has thousands of "items", if that makes a difference)

At first you should decode your json data like:
// will decode json data as assoc array
$data = json_decode($json_data, true);
Then, you can get value in this array like:
$item01 = $data['result']['items'][0];
$name = $item01['name']; // New York
$code = $item01['code']; // 7294
Or
// will decode json data as object
$data = json_decode($json_data);
$item01 = $data->result->items[0];
$name = $item01->name; // New York
$code = $item01->code; // 7294

You can iterate through items in result of your JSON object, and check for equality with the desired code, and each item's code. Here's how you would implement it into a function.
function getNameFromCode($json, $code) {
foreach ($json['result']['items'] as $item)
if ($item['code'] == $code)
return $item['name'];
// return false if the code wasn't found.
return false;
}
// assume this is the JSON string of your example.
$json_string = "...";
// pass true as the second argument to get an associative array.
$json = json_decode($json_string, true);
// should return "Los Angeles".
$name = getNameFromCode($json, 9182);
Documenation on foreach().

foreach( json_decode($my_json_string) as $key => $item)
if ( $item['code'] === $code ) { $name = $item[name]; break; }

You can convert JSON to PHP object and loop through the items with foreach loop.
function getNameByCode($phpobj, $code){
if( isset($phpobj->result) ){
if( isset($phpobj->result->items)
&& is_array($phpobj->result->items) ){
foreach($phpobj->result->items as $item){
if( $item->code == $code ){
return $item->name;
}
}
}
}
return false;
}//end function
You can test with this ... NOTE: trailing commas are removed as suggest by rjdown in comment
$json = '{
"result": {
"items": [
{
"name": "New York",
"code": 7294
},
{
"name": "Miami",
"code": 392
},
{
"name": "Los Angeles",
"code": 9182
}
]
}
}';
$phpobj = json_decode($json);
$name = getNameByCode($phpobj, "7294");
echo $name;

Related

how to search inside two JSON files at a time in PHP

I have two JSON files of same format, forexample
1st JSON File
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 1,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "Joe Biden",
"email": "joe#mail.com"
}
},
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "MULTIMEDIA PLUMBUM",
"email": "mdi#mail.com"
}
}
]
}
}
}
}
2nd JSON file
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 2,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW7dQ8N",
"name": "Mark",
"email": "mark#mail.com"
}
},
{
"node": {
"id": "QnVzaW5l5Gy9",
"name": "Trump",
"email": "trump#mail.com"
}
}
]
}
}
}
}
Each user has a unique "id", I want to get their id by searching their name in php, how can I do this
This is my PHP script
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
foreach ($result2 as $k => $v) {
if ($v['data']['business']['edges']['customers']['node']['name'] == "Trump") break;
}
echo $result[$k]['data']['business']['edges']['customers']['node']['name']; //I want to get id for trump "QnVzaW5l5Gy9"
Each user has a unique "id", I want to get their id by searching their name in php. How can I get id by searching name in both files at a time?
Thanks
Since you are looping through json file it will search inside of "data" so you can't use $v['data']
Also since edges is also array that have same values and you want to search inside of it you must make loop on that also
Here is example
foreach ($result2 as $k => $v) {
foreach ($v['business']['customers']['edges'] as $val) {
if ($val['node']['name'] == 'Trump') {
echo '<pre>';
// and now you can access any of those values, echo $val['node']['id'];
print_r($val['node']);
echo '</pre>';
}
}
}
Output
Array
(
[id] => QnVzaW5l5Gy9
[name] => Trump
[email] => trump#mail.com
)
EDIT
Since you want to search in both files at a same time you can put them into array and then use it like this
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$joined_result = array($result1, $result2);
foreach($joined_result as $val) {
// this will take all nodes where you will search
$node = $val['data']['business']['customers']['edges'];
foreach ($node as $value) {
if ($value['node']['name'] == 'Trump') {
echo '<pre>';
print_r($value['node']);
echo '</pre>';
}
}
}
You have two questions there, no?
The first question I get is "How to get the ID for a certain name"
$node = $result2['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
Almost your code, but I echo the ID when the name matches "Trump".
The second question I see is "How do search both json data at once"
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$all_data = [$result1, $result2];
foreach($all_data as $data) {
$node = $data['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
}
Transforming both json data to be in an array and then simply looping over the whole array should do the trick.

Getting JSON data from website returns " string(0) "

I;m trying to get data from a website using the following code:
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
var_dump($content);
$json = json_decode($content, true);
var_dump($json);
for ($idx = 0; $idx < count($json); $idx++) {
$obj = (Array)$json[$idx];
echo 'result' . $obj["name"];
}
?>
Which is getting me this result:
string(0) "" NULL
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
echo "<pre>";
//print_r($content);
$data = json_decode($content);
print_r($data); //Show the json decoded data comes form $url
##Parse this array {$data} using foreach loop as your use
?>
There are no numeric keys in the json returned from the url you posted in your question. So iterating through the associative array with numeric keys returns nothing.
This is the structure of the json you are working with:
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_sprite.gif?id=4798",
"icon_large": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_big.gif?id=4798",
"id": 4798,
"type": "Default",
"typeIcon": "http://www.runescape.com/img/categories/Default",
"name": "Adamant brutal",
"description": "Blunt adamantite arrow... ouch.",
"current": {
"trend": "neutral",
"price": 529
},
"today": {
"trend": "neutral",
"price": 0
},
"members": "true",
"day30": {
"trend": "negative",
"change": "-9.0%"
},
"day90": {
"trend": "negative",
"change": "-20.0%"
},
"day180": {
"trend": "negative",
"change": "-31.0%"
}
}
}
Try accessing $json["item"]. That should give you something more meaningful to work with. If you want to iterate over the key/value pairs in the item, use a foreach loop:
foreach($json["item"] as $key => $value) {
echo $key . ":";
print_r($value);
}

How to Parse JSON with PHP?

I can do a var_dump, but when trying to access the values, I am getting errors about the values not being found.
{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}
I used the following so far to try and parse it.
$json_file = file_get_contents('test.json');
$json_a = json_decode($json_file,true);
var_dump(json_decode($json_file)); //This works
echo $json_a['name']; //I want to print the name of each (from timers).
Try:
$yourDecodedJSON = json_decode($yourJson)
echo $yourDecodedJSON->metrics->timers[0]->name;
Or you can:
$yourDecodedJSON = json_decode($yourJson, true); // forces array
echo $yourDecodedJSON['metrics']['timers'][0]->name;
In your case, you may want to..
foreach($yourDecodedJSON['metrics']['timers'] as $timer){
echo $timer['name']; echo $timer['duration_ms']; // etc
}
If something fails, use:
echo json_last_error_msg()
To troubleshoot further
You need do it in following manner:-
<?php
$data = '{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}';
$new_array = json_decode($data); //convert json data into array
echo "<pre/>";print_r($new_array); //print array
foreach ($new_array->metrics->timers as $new_arr){ // iterate through array
echo $new_arr->name.'<br/>'; // rest you can do also same
}
?>
Output:- https://eval.in/407418

Delete from JSON with PHP

I'm trying to delete an item from a JSON file using the id of the item.
This is the code I'm using to do so.
if($id){
header('Content-Type: application/json');
$id = $_GET['id'];
$file = file_get_contents("data.json");
$json = json_decode($file);
foreach ($json->items as $item) {
if ($item->id == $id) {
unset($item);
file_put_contents('data.json', json_encode($json));
header('HTTP/1.1 204 No Content');
}
}
}
The RESTclient I'm using gives the 204 but when I look in my JSON file, the item is still there.
Any idea what I'm doing wrong?
EDIT
JSON looks like this
{
"items": [
{
"id": 1,
"title": "title",
"artist": "artist",
"genre": "genre",
"links": [
{
"rel": "self",
"href": "link/webservice/music/1"
},
{
"rel": "collection",
"href": "link/webservice/"
}
]
},
Inside a foreach-loop the copy of the array element you've got does not affect the original array in some ways.
You need to dereference the array item using the original array or pass it to the loop by reference.
The following should work, I guess:
if($id){
header('Content-Type: application/json');
$id = $_GET['id'];
$file = file_get_contents("data.json");
$json = json_decode($file);
foreach ($json->items as $key => $item) {
if ($item->id == $id) {
unset($json->items[$key]);
file_put_contents('data.json', json_encode($json));
header('HTTP/1.1 204 No Content');
}
}
}

json object is bahaving wrongly

I am test-running a web application
where in json is required. I have the following json
structure:
{
"Articles": [
{
"Article": {
"ID": 111,
"title": "Idiot",
"author": "Moron",
"pubDate": "11/2/14",
"summary": "bla bla bla"
},
"Article": {
"ID": 222,
"title": "wisdom",
"author": "wise one",
"pubDate": "11/2/15",
"summary": "ha ha ha"
}
}
]
}
I then decided to check if a matching ID exits before adding
any record. To this effect, I wrote a method, encased it within
a JSon class as follows:
public function ID_Exists($ID){
$file = file_get_contents($this->FileName, true);
$data = json_decode($file, false); //get json in array string format
foreach($data as $child){
foreach($child as $item){
if($item->ID == $ID){
echo 'Exists';
}else{
echo 'Non Existent';
}
}
}
}
I test-ran it like:
$Obj = new JSon('file.json'); //knows what to do
if($Obj->ID_Exists(111)){
//ok ! no problem
}else{
////no problem
}
Here's the output I got:
Undefined property: stdClass::$ID in
C:\Server\wamp\www\Oweb\libs\dmanager.php on line 635
What am I doing wrong? I don't want to use the array
format of json_decode().
Your JSON structure is impossible. Articles is an array which contains a single object which contains the key Article twice - this cannot work.
Your structure needs to be:
{
"Articles": [
{
"ID": 111,
...
},
{
"ID": 222,
...
}
]
}
Which you can traverse using:
$data = json_decode($json);
foreach ($data->Articles as $article) {
if ($article->ID == ..) ..
}

Categories