I'm trying to parse a JSON file which looks like this,
[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "",
"url": ""
}
]
I'm trying to get the desc object from the array with the name Development Task, the system needs to be dynamic so I can't just use json_o[0](desc);
I've tried different methods such as foreaching the data multiple times but I still can't think of a solution, any help would be great, cheers.
Try with this:
$jsonData = '[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "",
"url": ""
}
]';
$encoded = json_decode($jsonData);
foreach($encoded as $data)
{
if('Development Task' == $data->name)
{
echo $data->desc;
}
}
If you search for dynamic fields, i would have gone with :
$jsonData = '[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "FirstDescription",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "SecondDescription",
"url": ""
}
]';
$arrayFromJson = json_decode($jsonData, true);
function searchByKey($keyToSearchIn, $searchName, $array) {
foreach ($array as $key => $val) {
if ($val[$keyToSearchIn] == $searchName) {
return $val['desc'];
}
}
return null;
}
$return = searchByKey("name", "Development Task", $arrayFromJson);
So
var_dump($return);
returns
string(16) "FirstDescription"
Note : If you only need a search by name, you can change the function with :
function searchByName( $searchName, $array) {
foreach ($array as $key => $val) {
if ($val['name'] == $searchName) {
return $val['desc'];
}
}
return null;
}
$return = searchByName("Development Task", $arrayFromJson);
Hope it helps.
The comments in the code explain what happens:
$jsonData = '[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "moocow",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "wowcow",
"url": ""
},
{
"id": "539eebe09rb42c971d46b9ba1",
"name": "Development Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "sowccow",
"url": ""
}
]';
$encoded = json_decode($jsonData, true); //converts the json object to an array
foreach ($encoded as $arrayObject){
if( in_array("Development Task", $arrayObject) ){
print_r($arrayObject['desc'] . "\n");
}
}
-> moocow sowccow
based upon
I'm trying to get the desc object from the array with the name Development Task
This should do what you want and you can easily take the string and make it a variable. There are plenty of built-in functions on PHP.net that are tuned and are probably 10x better than rolling your own code.
Related
I have a JSON file which contains some movie data:
[{
"title": "Bad Company",
"desc": "------------------------",
"rating": "6.0",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اكشن"
}, {
"title": "The Pinch",
"desc": "------------------------",
"rating": "6.1",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اكشن , جريمه"
}, {
"title": "Catskill Park",
"desc": "------------------------",
"rating": "6.2",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "خيال علمي , رعب"
}, {
"title": "Klippers",
"desc": "------------------------",
"rating": "5.3",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اثاره , اكشن"
}, {
"title": "Psycho",
"desc": "------------------------",
"rating": "5.6",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اثاره , دراما"
}]
I need to add all titles to a drop down menu, and when a user selects an item from the menu show the desc, image and category.
by php
Can anyone help me please?
my traying code
$url = 'http://localhost/ar.json';
$xx = json_decode(file_get_contents($url));
$data = json_decode($xx, true);
$search='title';
foreach($data['meta_data'] as $d){
if($d['key']==$search){
$found=$d['value'];
break;
}
}
echo $found?$found:"$search not found";
Assuming the structure, which you do not fully how us, is correct.
Use the key and value method of a foreach like this
$url = 'http://localhost/ar.json';
$xx = json_decode(file_get_contents($url));
$data = json_decode($xx, true);
$search='title';
$found = false;
foreach($data['meta_data'] as $key => $val){
if($key == $search){
$found = $val;
break;
}
}
echo $found ? $found : "$search not found";
I'm trying to parse data returned by the Jotform API.
I'm successfully echoing the data but I'm also getting unnecessary additional lines of text.
My PHP code is:
include "JotForm.php";
$jotformAPI = new JotForm("myapikey");
$submissions = $jotformAPI->getFormSubmissions("myformid");
var_dump($submissions );
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
foreach ($detail as $d) {
echo $d[1]['answer']['first'] . '<br>';
}
}
result of var_dump($submissions );
{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}],
}
And here is the result I'm getting:
1
0
0
0
C
0
LeBron
I had to repair your invalid json string...
Code: (Demo)
$json = '{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}}]
}';
foreach (json_decode($json, true)['content'] as $set) {
echo "{$set['answers'][1]['answer']['first']} {$set['answers'][1]['answer']['last']}\n";
}
Output:
LeBron James
I'm a little fuzzy on the action of the jot functions, but maybe it's supposed to be like this:
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
echo $detail['answers'][1]['answer']['first'] . '<br>';
}
I am trying to parse a xml to a nested json structure with php.
This is my test script:
$json_drives = array();
foreach($drives->DR as $dr){
$current_drive = array();
$current_drive['id'] = $dr->ID;
$current_drive['name'] = $dr->NAME->D;
$json_drives[] = $current_drive;
}
echo("Finished");
// Parse and save
$f = json_encode($json_drives);
file_put_contents('test12345.json', $f);
I get a structure like that:
[
{
"id": {
"0": "1"
},
"name": {
"0": "Name 1"
}
},
{
"id": {
"0": "2"
},
"name": {
"0": "Name 2"
}
},
// ...
]
But I dont want the keys "id" and "name" to be nested. It should look like this:
[
{
"id": "1"
"name": "Name 1"
},
{
"id": "2"
"name": "Name 2"
},
// ...
]
How can I handle that?
Assuming your JSON's "drive" objects will always have this structure:
"id": {
"0": "Some ID"
},
"name": {
"0": "Some name"
}
You can use:
$current_drive['id'] = ((array) $dr->ID)[0];
$current_drive['name'] = ((array) $dr->NAME->D)[0];
How can I read several values with the same name from a JSON from Facebook, when I use this code:
$urlamandar = 'https://graph.facebook.com/'.$user."?access_token=".$access_token;
$content = file_get_contents($urlamandar);
$obj = json_decode($content, true);
$obj = json_decode($content);
It displays this:
{
"id": "XXXXXXXX",
"name": "Ricardo Capistran",
"first_name": "Ricardo",
"last_name": "Capistran",
"gender": "male",
"locale": "es_MX",
"username": "richycapy"
}
And since because there is only one ID, one NAME, one USERNAME, etc, Its quite simple place them in vars like so:
$fbuserid = $obj->{'id'};
$fbname = $obj->{'name'};
$fbusername = $obj->{'username'};
$fbemail = $obj->{'email'};
$fbbirthday = $obj->{'birthday'};
But when it comes to larger files like this code:
$urlamandar = 'https://graph.facebook.com/'.$user.'/albums?access_token='.$access_token;
Its displays a way bigger array like so:
{
"data": [
{
"id": "10150732237818223",
"from": {
"name": "Ricardo Capistran",
"id": "XXXXXXX"
},
"name": "EnterateNorte.com Photos",
"link": "https://www.facebook.com/album.php?fbid=10150732237818223&id=743158222&aid=457026",
"privacy": "custom",
"count": 31,
"type": "app",
"created_time": "2012-03-11T02:44:42+0000",
"updated_time": "2014-01-07T03:13:24+0000",
"can_upload": false
},
{
"id": "440168313222",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Timeline Photos",
"link": "https://www.facebook.com/album.php?fbid=440168313222&id=743158222&aid=220377",
"cover_photo": "10151730849598223",
"privacy": "everyone",
"count": 175,
"type": "wall",
"created_time": "2010-06-30T22:38:45+0000",
"updated_time": "2014-01-01T02:09:11+0000",
"can_upload": false
},
{
"id": "10150797320378223",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Instagram Photos",
"link": "https://www.facebook.com/album.php?fbid=10150797320378223&id=743158222&aid=466555",
"cover_photo": "10151695050098223",
"privacy": "friends",
"count": 37,
"type": "app",
"created_time": "2012-04-09T23:50:08+0000",
"updated_time": "2013-12-29T08:29:15+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NDM1NjY5NjI4MjIy",
"before": "MTAxNTA3MzIyMzc4MTgyMjM="
},
"next": "https://graph.facebook.com/*my_id*/albums?access_token=*access_token*&limit=25&after=NDM1NjY5NjI4MjIy"
}
}
And I would need the “name” and “id” off all the albums, so then I can repeat this same procedure with the containing pictures
Obviously it has way more albums, I just cut it after 3 just to explain my self…
Is there a way to place them in vars? With a php “for each” some how
Thanks!
You can do something like
$obj = json_decode($content, true);
$array_album = array();
foreach($obj['data'] as $key=>$val){
$array_album[] = array("id"=>$val["id"],"name"=>$val["name"]);
echo "ID : ".$val["id"]. " NAME : ".$val["name"] ;
echo "<br />";
}
print_r($array_album); // This will have all the id and names
If you dont want to store in array then the names and id will appear in the above loop and you can do whatever you want with those values. Or use the array $array_album and loop through if you want to use it later.
I have a list of movies and I want to compare to the Array of movies i got from Facebook Graph API.
Here is an example of what API is getting:
{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}...
The list I need to compare is pretty big, but here are some:
Wall Street, Shooter, Young Guns, Due Date...
Basically just compare 'Name' in 'data' with 'my list' of Movie titles. But can't figure out the syntax
Something like:
if ($movies->data->name == 'movie titles list') {echo "You like the same movies";}
I found this:
if (in_array('movie titles list', $a)) {echo "You like the same movies";}
Any thoughts would help me out.
Thanks
The data looks to be JSON encoded...
Try something like this: (json_decode)
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}]}';
$json_to_array = json_decode($large_data, true);
var_dump(json_decode($large_data, true));
// You should now be able to compare the two array
echo print_r($json_to_array,true);
EDIT:
Improving on what #Eric posted
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}]}';
$movie_list = json_decode($large_data, true);
$movieNames = array();
foreach($movie_list as $movies) {
foreach($movies as $movie) {
$movieNames[] = $movie['name'];
}
}
$myMovies = array('Wall Street', 'Shooter', 'Young Guns', 'Due Date');
$common_movies = array_intersect($movieNames, $myMovies);
foreach($common_movies as $common_movie) {
echo "We like the same movie ".$common_movie."<br />\n";
}
Another method:
<?php
$json_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}
]}';
$array_data = json_decode($json_data, TRUE);
$compare_list = array(
'Wall Street',
'Shooter',
'Young Guns',
'Due Date'
);
// <Marco Stumper> phpundhtml at web dot de
function in_array_multi($needle, $haystack) {
$found = false;
foreach ($haystack as $value) {
if ((is_array($value) && in_array_multi($needle, $value)) || $value == $needle) {
$found = true;
}
}
return $found;
}
foreach ($compare_list as $item) {
echo '<p>' . $item . (in_array_multi($item, $array_data) ? ' DOES ' : ' does NOT ') . 'exist within $array_data</p>' . PHP_EOL;
}
?>
Output:
<p>Wall Street does NOT exist within $array_data</p>
<p>Shooter DOES exist within $array_data</p>
<p>Young Guns does NOT exist within $array_data</p>
<p>Due Date does NOT exist within $array_data</p>
Use array_intersect(array1, array2, ... arrayN)
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}
]}';
$movies = json_decode($large_data, true)['data'];
$movieNames = array();
//Get only the name from the movie list
foreach($movies as $movie) {
$movieNames[] = $movie['name'];
}
//Intersect with internal list
print_r(array_intersect($movieNames, $myMovies));