Retrieve data from JSON based on the object index in PHP [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a $abcd variable and the following is the output:
echo $abcd;
//Output:
{
"NID": 2,
"STS": "3",
"Options": {
"Model": "model value",
"Location": "location value",
"Price": "price value",
"Name": "Value"
}
}
In the "Options" I have 3 names and values of each. The names are not fixed and could be anythings and the number of objects in Options could be any from 0 to 100.
I'd like to know if there is any way (JSON format preferred) that I can assign the Names and their related values to two other variables.
$varName[0]=Model
$varValue[0]=model value
$varName[1]=Location
$varValue[1]=location value
$varName[2]=Price
$varValue[2]=price value

i'm not sure what is th logic behind this,
but you may accomplish this by using mix of array_key & array_values like following:
$abcd = '{
"NID": 2,
"STS": "3",
"Options": {
"Model": "model value",
"Location": "location value",
"Price": "price value",
"Name": "Value"
}
}';
$data = json_decode($abcd, true);
$keys = array_keys($data['Options']);
$values = array_values($data['Options']);
echo $keys[0] . " - " . $values[0]; // Model - model value
echo $keys[1] . " - " . $values[1]; // Location - location value
// ..... and so on.
live example: https://3v4l.org/GggRd

$data = json_decode($abcd, true);
foreach($data['Options'] as $index => $value) {
//do whatever you want
}
//or access them directly
$data['Options']['Model']

You dont need to assign them to anything else, just json_decode() the JSONString and they become a PHP Object you can use as is
$obj = json_decode($abcd);
echo $obj->Options->Model;
echo $obj->Options->Location;
echo $obj->Options->Price;
RE your comment#
I said that the names are varies and Model, Location and Price is just an example
then you could do
foreach ($obj->Options as $prop => $val) {
sprintf( '%s = %s', $prop, $val );
}

Related

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

Get values from JSON array in PHP with the following format?

I have got this array from the Android developer whom I am working with and I have to get the values of the key name from the following array:
[
{
"data":"[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
"status":1
}
]
I have tried doing the following:
<?php
$s = '[
{
"data": "[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
"status": 1
}
]';
$obj = json_decode($s,true);
echo $obj[0]['data']
?>
Which gives me following output:
[
{
"name": "step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd "
},
{
"name": "step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf"
},
{
"name": "step 3 kkkkkkkkkk"
},
{
"name": "step 4 ljlejrhlflhgf dfhjk"
}
]
But I want just the values of the key name like:
step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd
step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf
step 3 kkkkkkkkkk
.
.
.
My question is similar to this one:
Get value from JSON array in PHP
except the format is different.
Can I get the values in this format? If so, how? If not, is the format incorrect?
Assuming $obj[0]['data'] actually has the JSON that you posted, just decode and extract the name columns:
foreach(array_column(json_decode($obj[0]['data'], true), 'name') as $name) {
echo $name;
}
First of all you have not a json-structure inside the "data" field, but just a string, which contains json data.
Therefore you did it wrong, when convert the data into a constant value. You have to double all backslashes first.
Then you can get the "data" element and perform json_decode once more.
<?php
$s = '[
{
"data": "[{\\"name\\":\\"step 1 kdfhghdkgjdf\\\\nkjdhfgkjhdkjghd\\\\nkdfjhgkjdhfg\\\\n\\\\n\\\\ndfjhgkjdfjhgdfgd\\\\n\\"},{\\"name\\":\\"step 2 dhfgkjdfhkhkjchjkfd\\\\ndkjhjdf\\\\njhkdfhkghdkfhgkdhg\\\\n\\\\n\\\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\\"},{\\"name\\":\\"step 3 kkkkkkkkkk\\"},{\\"name\\":\\"step 4 ljlejrhlflhgf\\\\n\\\\n\\\\ndfhjk\\"}]",
"status": 1
}
]';
$obj = json_decode($s,true);
$data = json_decode($obj[0]['data'], true);
foreach($data as $item) {
print($item['name'] . "\r\n");
}

Extracting from subarray structure after json_decode [duplicate]

This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 7 years ago.
I'm new to PHP and I'm trying to use it to filter information from the New York Times' article search API. I'm still struggling to figure out how I can pull out the "web-url" and "snippet" from the JSON response even after looking through this similar question. I'm using json_decode to turn the response into an associative array. Here's my code
$data = file_get_contents($queryURL);
$jsondata = json_decode($data, true);
if (count($jsondata) != 0)
{
foreach($jsondata['response']as $key => $value)
{
echo "Key: " . $key . " Value: " . $value . " <br>";
}
}
This only prints out the words "array", "ok" and "copyright".
Here's a sample of the json:
"response": {
"meta": {
"hits": 25,
"time": 332,
"offset": 0
},
"docs": [
{
"web_url": "http://thecaucus.blogs.nytimes.com/2012/01/01/virginia-attorney-general-backs-off-ballot-proposal/",
"snippet": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"lead_paragraph": "DES MOINES -- Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"abstract": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"print_page": null,
"blog": [ ],
"source": "The New York Times",
"multimedia": [ ],
"headline": {
"main": "Virginia Attorney General Backs Off Ballot Proposal",
"kicker": "The Caucus"
},
Try this. You need to loop through each of the docs
foreach ($jsondata['response']['docs'] as $doc) {
echo "web_url: " . $doc['web_url'] . " snippet: " . $doc['snippet'];
}
When you are looping through $jsondata['response']
then when your $key is meta (Similarly for other keys as well like docs etc) its $value is an array i.e
array(
"hits"=> 25,
"time"=> 332,
"offset"=> 0
)
So when you are trying to echo this $value it prints array as its a property of echo in php to print arrays as string "array".
I hope this makes clear what you are doing wrong!!!
You might need to do something like this
foreach($jsondata['response']as $key => $value)
{
// check if $jsondata['response'][$key] is an array using is_array()
// handle as per array
}
Learn about is_array

Loop json array in php

I know it's been asked many times and I've gone through a good 15 - 20 questions trying to figure out how to get it to work.
JSON
{"menu": {
"title":"Title One",
"link":"Link One",
"title":"Title Two",
"link":"Link Two"}
}
PHP
$string = file_get_contents("test.json");
$json_a = json_decode($string,true);
foreach($json_a['menu'] as $key => $value) {
echo $key . ": " . $value . "<br />";
}
This so far only displays
title: Title Two
link: Link Two
as opposed to
title: Title One
link: Link One
title: Title Two
link: Link Two
Also am I correct in thinking $json_a[menu] does not need apostrophes because $json_a is not a function? it works with or without.
Thanks in advance.
You can't have multiple entries with the same key in an array. While JSON might allow it, when it's parsed by PHP, the last definition of the key,value pair wins.
It looks like menu should be an array of objects instead:
{
"menu": [{
"title":"Title One",
"link":"Link One"
}, {
"title":"Title Two",
"link":"Link Two"
}]
}
PHP
foreach($json_a['menu'] as $value) {
echo $value['title'] . ": " . $value['link'] . "<br />";
}

Get JSON objects in PHP, not array

Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}
I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.
You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num
First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...

Categories