json result to array and get result - php

I have simple API call for themoviedb.org and I get results by external id (imdb_id), but I can't parse and get correct value.
I just want get value of ID --> [id] => 18773
So how I can get stored only themoviedb ID from API?
My code:
$url = "https://api.themoviedb.org/3/find/".$imdbId."?api_key=$apikey&language=en-US&external_source=imdb_id";
$content = file_get_contents($url, false);
// Tried
$json = json_decode($content, true);
echo $json['id']; // return nothing?
// Testing (check below array return)
$result = array_values(json_decode($content, true));
print("<pre>".print_r($result,true)."</pre>");
Array from $result
Array
(
[0] => Array
(
[0] => Array
(
[adult] =>
[backdrop_path] => /iSaKc4Nu7hTQDAvJigUVmNwTkj6.jpg
[genre_ids] => Array
(
[0] => 27
[1] => 9648
[2] => 53
)
[id] => 18773
[original_language] => en
[original_title] => Doppelganger
[overview] => A woman moves from NYC to LA after a murder, in which she is implicated. She is followed by what is apparently her evil alter- ego. She moves into a room for rent by a writer, and he begins having an affair with her, but after some strange things happen, he's not so sure if the affair is with her or her doppelganger.
[poster_path] => /kdMJhjqAlwJekpp8jGu6Lk3Tfy6.jpg
[release_date] => 1993-03-01
[title] => Doppelganger
[video] =>
[vote_average] => 5
[vote_count] => 56
[popularity] => 5.931
)
)
[1] => Array
(
)
[2] => Array
(
)
[3] => Array
(
)
[4] => Array
(
)
)

According to the documentation: https://developers.themoviedb.org/3/find/find-by-id you can get the id value by something like this $json['movie_results'][0]['id'].
But as you can see, the object movie_results is an array so you may have there more than one result or even no results.
So here are some tips what you should consider in your code:
What to do if there are more than one results?
What to do if there are no result at all?
If there is only one result you can safely get the ID.

Related

PHP Get values from nested array

I am new to PHP and Arrays, I am trying to get the values from an array. But no matter how I'm trying to do it, I can't get the value. What am I doing wrong?
The Array:
Array ( [playerinfo] => Array ( [rank] => Godfather [cash] => € 8,520,530 [weapon] => M-16 (29000) [health] => Array ( [width] => 100 [color] => green ) [wealth] => Too rich to be true [protection] => Bulletproof Humvee [plf] => Huge [plane] => Concorde [crew] => None [pbf] => Large [ship] => None ) [character] => Array ( [crime] => Array ( [0] => 120 [1] => 69 ) [gta] => Array ( [0] => 400 [1] => 70 ) [drugs] => Array ( [0] => 120 [1] => 2528 ) [airport] => Array ( [0] => 2700 [1] => 2529 ) [oc] => Array ( [0] => 86400 [1] => 1442364 ) [tr] => Array ( [0] => 10800 [1] => 1640016011 ) [plf] => Array ( [0] => 7200 [1] => 6712 ) [kill] => Array ( [0] => 3600 [1] => 1640019611 ) ) )
The way I tried to get the info:
$AccData = json_decode($MobinfoString, true);
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['cash'].'<br/>';
foreach ($AccData as $playerinfo) {
echo $playerinfo['playerinfo']['rank'].'<br/>';
echo $playerinfo['character']['gta'].'<br/>';
}
EDIT:
The json string
{"playerinfo":{"rank":"Boss","cash":"€ 5,923,712","weapon":"M-16 (4500)","health":{"width":"100","color":"green"},"wealth":"Too rich to be true","protection":"Bulletproof Humvee","plf":"Huge","plane":"Concorde","crew":"None","pbf":"Large","ship":"None"},"character":{"crime":[120,122],"gta":[400,369],"drugs":[120,2582],"airport":[2700,2582],"oc":[86400,1640020450],"tr":[10800,1640016850],"plf":[7200,3935],"kill":[3600,1640020450]}}
Anyone knows how to do this ? For example I need the Concorde from plane in a variable and the time values from gta in a variable. And some more from this string.
So your first Part is okay and you rank you can just display like the first part as well
$AccData = json_decode($MobinfoString, true);
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['cash'].'<br/>';
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['plane'].'<br/>';
echo $AccData['character']['gta'][0].'<br/>';
but the character is on the same level as playerinfo so you need to access it from AccData. also gta is an array like health, so you have to specify which value you want to show, the first so 0 or second which is 1

Getting out the value of a key in multidimentional array in php

In my php query I got this output:
{"projects":[{"id":127,"name":"efrat","status":{"id":10,"name":"development","label":"development"},"description":"","enabled":true,"view_state":{"id":10,"name":"public","label":"public"},"access_level":{"id":90,"name":"administrator","label":"administrator"},"custom_fields":[{"id":1,"name":"Customer email","type":"email","default_value":"","possible_values":"","valid_regexp":"","length_min":0,"length_max":50,"access_level_r":{"id":10,"name":"viewer","label":"viewer"},"access_level_rw":{"id":10,"name":"viewer","label":"viewer"},"display_report":true,"display_update":true,"display_resolved":true,"display_closed":true,"require_report":false,"require_update":false,"require_resolved":false,"require_closed":false}],"versions":[],"categories":[{"id":93,"name":"Monitor","project":{"id":0,"name":null}},{"id":31,"name":"Proactive","project":{"id":0,"name":null}},{"id":30,"name":"Project","project":{"id":0,"name":null}},{"id":29,"name":"Support","project":{"id":0,"name":null}}]}]}
after using 'json_decode' method on it, I get this:
"(
[projects] => Array
(
[0] => Array
(
[id] => 127
[name] => myprojectname
[status] => Array
(
[id] => 10
[name] => development
[label] => development
)
[description] =>
[enabled] => 1
[view_state] => Array
(
[id] => 10
[name] => public
[label] => public
)
[access_level] => Array
(
[id] => 90
[name] => administrator
[label] => administrator
)
[custom_fields] => Array
(
[0] => Array
(
[id] => 1
[name] => Customer email
[type] => email
[default_value] =>
[possible_values] =>
[valid_regexp] =>
[length_min] => 0
[length_max] => 50
[access_level_r] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[access_level_rw] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[display_report] => 1
[display_update] => 1
[display_resolved] => 1
[display_closed] => 1
[require_report] =>
[require_update] =>
[require_resolved] =>
[require_closed] =>
)
)
[versions] => Array
(
)
[categories] => Array
(
[0] => Array
(
[id] => 93
[name] => Monitor
[project] => Array
(
[id] => 0
[name] =>
)
)
[1] => Array
(
[id] => 31
[name] => Proactive
[project] => Array
(
[id] => 0
[name] =>
)
)
[2] => Array
(
[id] => 30
[name] => Project
[project] => Array
(
[id] => 0
[name] =>
)
)
[3] => Array
(
[id] => 29
[name] => Support
[project] => Array
(
[id] => 0
[name] =>
)
)
)
)
)
)"
In my PHP, how can I release the "name" object value (the result should be 'myprojectname') from this array? I've tried many foreach loops that got me nowhere.
Thank you,
It looks like you have one object, that when decoded actually only has one array item. So, in your case, ‘myprojectname’ may simply be “$projects[0][‘name’]”
If many array items, you could
foreach ($projects as $project) {
echo $project[‘name’];
}
EDIT: I took object provided and json_decoded it myself, it doesn't match the json_decoded item presented by OP -- the first image shows the code to var_dump 'name' OP desired, part of the code also below:
$decoded = json_decode($obj);
$projects = $decoded->projects;
$name = $projects[0]->name;
Your 'projects' contains an array ("projects":[{"id":127, ... }]). I assume that the 'projects'-array might contain multiple 'project'-objects like this?
{
"projects":
[
{
"id":127,
"name":"my-project"
},
{
"id":128,
"name":"my-other-project"
}
]
}
In that case you need the arrow notation to access the name property, for example:
foreach ($projects as $project_object) {
foreach ($project_object as $project) {
echo $project->name . '<br/>';
}
}
EDIT:
I took a minimal code example of the OP and got the expected result:
Can you add more details in your code snippets in your original question or provide us with a working example of your code?
There are some online PHP sandboxes that can help you with this. For example: I stripped out all code that does not seem related to your question and got the result you are looking for in two different ways:
http://sandbox.onlinephpfunctions.com/code/009c53671fd9545e4fcecfe4b0328974381ee2ce
It is also a good idea to sum up all the foreach loops that you already tried, so we can see if you were nearly there with your own solution. This way we can understand your question better and it prevents us from offering solutions that you already used.

PHP efficiently accessing values in a JSON array on different levels

Working on a personal project that will pull results from an API with full details of each pokemon.
So far I got the contents of the URL and returned the results into a JSON array format.
At the moment I am stuck on trying to retrieve results for[stats] inside from the array in an efficient manner.
private function getGenOnePokemon()
{
// the url of the api
$url = $this->baseUrl;
//get the contents of $url var and decode it into a json array
$json = file_get_contents($url , true);
$pokemon = json_decode($json, true, JSON_UNESCAPED_UNICODE);
// array output of pokemon
echo '<pre> ';
print_r($pokemon);
echo'</pre>';
//echo out value as speed
foreach($pokemon['results'][0] as $happy)
{
echo $happy['name'] . '<br />';
}
// echo base_stat value for speed with value of 90
echo $pokemon['stats'][0]['base_stat'];
}
However I do not seem to get anywhere much printing values/keys as I need to add something else to have full access to the values?
Would prefer not to directly access results, like I am doing with base_stat as plan on using this logic to pass into HTML View layer later.
Example of print_r dump (not full dump as really long) Full example: https://pokeapi.co/api/v2/pokemon/pikachu
Array
(
[forms] => Array
(
[0] => Array
(
[url] => https://pokeapi.co/api/v2/pokemon-form/25/
[name] => pikachu
)
)
[abilities] => Array
(
[0] => Array
(
[slot] => 3
[is_hidden] => 1
[ability] => Array
(
[url] => https://pokeapi.co/api/v2/ability/31/
[name] => lightning-rod
)
)
[1] => Array
(
[slot] => 1
[is_hidden] =>
[ability] => Array
(
[url] => https://pokeapi.co/api/v2/ability/9/
[name] => static
)
)
)
[stats] => Array
(
[0] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/6/
[name] => speed
)
[effort] => 2
[base_stat] => 90
)
[1] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/5/
[name] => special-defense
)
[effort] => 0
[base_stat] => 50
)
[2] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/4/
[name] => special-attack
)
[effort] => 0
[base_stat] => 50
)
[3] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/3/
[name] => defense
)
[effort] => 0
[base_stat] => 40
)
[4] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/2/
[name] => attack
)
[effort] => 0
[base_stat] => 55
)
[5] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/1/
[name] => hp
)
[effort] => 0
[base_stat] => 35
)
)
Any advice on how to access the data using foreach or other tips greatly appreciated. Thank you!
PHP has a specific function designed to target columnar data from arrays. It is called array_column()
If you want to isolate all of the name elements inside the forms subarray, use this:
$names=array_column($pokemon['forms'],'name');
If you want to isolate all of the base_stat elements inside of the stats subarray, use this:
$base_stats=array_column($pokemon['stats'],'base_stat');
Now you will have $names and $base_stats which are single-dimensional arrays by which you can perform additional processes or return from the function. Clean, intuitive, and simple.
Your $pokemon array doesn't contain a results field. There's only an forms field. So you should iterate over forms to print the names of the forms.
foreach($pokemon['forms'] as $happy) {
echo $happy['name'] . '<br />';
}
You could do the same thing with the stats
foreach($pokemon['stats'] as $stat) {
$base_stat = $stat['base_stat'];
// ...
}

Extract data fron JSON array using loop

im trying to filter a JSON array response as i only need a small part of the results.
I need to get the players displayName only.
Here is the repose for the first player, there can be upto 12 player per match.
I need something that can loop through and extract the names..
[displayName] => jonhofun
At present the only way i can get the data i need is by doing
$player1 = $json11['Response']['data']['entries']['0']['player']['destinyUserInfo']['displayName'];
$player2 = $json11['Response']['data']['entries']['1']['player']['destinyUserInfo']['displayName'];
etc... etc...
heres the original response
Array
(
[Response] => Array
(
[data] => Array
(
[period] => 2016-08-20T10:16:46Z
[activityDetails] => Array
(
[referenceId] => 3156370656
[instanceId] => 5370359303
[mode] => 12
[activityTypeHashOverride] => 3614615911
)
[entries] => Array
(
[0] => Array
(
[standing] => 0
[score] => Array
(
[basic] => Array
(
[value] => 2190
[displayValue] => 2,190
)
)
[player] => Array
(
[destinyUserInfo] => Array
(
[iconPath] => /common/destiny_content/icons/d0d3cd4c26aa1a931d46c4bf720856ba.jpg
[membershipType] => 2
[membershipId] => 4611686018454971653
[displayName] => jonhofun
)
[characterClass] => Warlock
[characterLevel] => 40
[lightLevel] => 322
)
)
)
)
)
)
Any help would be appreciated.
You need to loop through the sub array under "entries".
foreach ($json11['Response']['data']['entries'] as $entries) {
$player_names[] = $entries['player']['destinyUserInfo']['displayname'];
}
echo "<pre>";
print_r($player_names); // Check all player names

Issue getting info out of array

I'm trying to get info out of this information:
Array (
[result] => success
[totalresults] => 1
[startnumber] => 0
[numreturned] => 1
[tickets] => Array (
[ticket] => Array (
[0] => Array (
[id] => 7
[tid] => 782755
[deptid] => 1
[userid] => 39
[name] => Mark Lønquist
[email] => mark.loenquist#outlook.com
[cc] =>
[c] => 79rzVBeJ
[date] => 2013-04-25 16:14:24
[subject] => test
[status] => Open
[priority] => Medium
[admin] =>
[attachment] =>
[lastreply] => 2013-04-25 16:14:24
[flag] => 0
[service] =>
)
)
)
)
The results are printed using:
print_r($results);
Usually, I've been able to do a simple:
$var = $results['something'];
To get it out, but it wont work with this :( Any help is appreciated.
After reformatting the array you pasted, it becomes clear that some elements are nested several levels deep. (It's a "multidimensional array"; see example #6 in the docs.) In those cases, you have to add additional brackets containing each successive key to reach the depth you want. For example, a sample from your $results array:
Array (
[result] => success
[totalresults] => 1
...
[tickets] => Array (
[ticket] => Array (
[0] => Array (
[id] => 7
[tid] => 782755
...
)
)
)
)
You simply need to do $results['totalresults'] to access "totalresults", but to get "tid" you would need to use $results['tickets']['ticket'][0]['tid'].
If you want to get "tid" from all of the tickets when there are multiple, you will have to iterate (loop) over the array of tickets. Probably something like this (untested, but should be close enough for you to figure out):
foreach ($results['tickets']['ticket'] as $ticket) {
echo $ticket['tid'];
}
To see what the problem is with your print_r() you may add error_reporting(E_ALL); to the top of your code.
Note that if you want to retrieve the value for a key such as 'totalresults' then $results['totalresults'] would be sufficient.
However, if you want to get a key from one of the nested arrays such as email then you would have to use $results['result']['tickets']['ticket'][0]['email'].

Categories