PHP efficiently accessing values in a JSON array on different levels - php

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'];
// ...
}

Related

json result to array and get result

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.

JSON Decode save array

I am able to receive the following JSON data with the following PHP code:
$json = file_get_contents('https://xxxx');
$data = json_decode($json,true);
$forex = $data['items'];
echo "<pre>";
print_r($forex);
exit;
This gives me the following JSON data:
Array
(
[0] => Array
(
[new] =>
[data] => Array
(
[direction] => 1
[pip] => 0
[exchange] => FOREX
[symbol] => USDCHF
[interval] => 15
[pattern] => Resistance
[complete] =>
[identified] => 2020-02-26T14:45:00.000Z
[age] => 0
[length] => 259
[found] => 2020-02-26T14:45:56.381Z
[result_type] => KeyLevel
[result_uid] => 642525551
[prediction_price_from] => 0
[prediction_price_to] => 0
[group_name] => FX Majors
[symbol_name] => USDCHF
[symbol_id] => 0
[analysis_text] => Approaching Resistance level of 0.9800 identified at 2/26 14:45. This pattern is still in the process of forming. Possible bullish price movement towards the resistance 0.9800 within the next 15 hours.
[expires_at] => 2020-02-27T05:48:36.701Z
)
[links] => Array
(
[0] => Array
(
[rel] => detail
[href] => https://xxxx
)
[1] => Array
(
[rel] => analysis
[href] => https://xxxx
)
[2] => Array
(
[rel] => chart-xs
[href] => https://xxxx
)
[3] => Array
(
[rel] => chart-sm
[href] => https://xxxx
)
[4] => Array
(
[rel] => chart-md
[href] => https://xxxx
)
[5] => Array
(
[rel] => chart-lg
[href] => https://xxxx
)
[6] => Array
(
[rel] => icon-arrow
[href] => https://xxxx
)
)
)
What I am trying to do is to save the information into my MySQL database, however I am unable to get the data displayed even by testing to echo the data:
foreach($forex as $info) {
echo $info->symbol . '<br>';
}
Anyone with a possible solution for me to save the data or even enable me to display the data for each Array (Example: symbol, pattern, link chart-md).
Below the commented code:
//Save json text into variable $json
$json = file_get_contents('https://xxxx');
//Convert json into PHP array
$data = json_decode($json,true);
//Set $forex as $data['items'];
$forex = $data['items'];
//Print
echo "<pre>";
print_r($forex);
exit;
$forex is a PHP array variable (not a JSON string).
You could save your data into MySQL VARCHAR[Length] field using json string variable $json instead of PHP array $forex.
When you need to get the data from DB and display it, you could get JSON data from MySQL and convert it from JSON to Array using PHP json_decode($json,true).
If you want to use a value into a PHP array, use $info["symbol"] instead of $info->symbol

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

How can I merge or search an object?

Here's my issue:
I have an object filled with arrays that look like this.
[376339] => Array
(
[0] => 1f422730-f54b-4e4d-9289-10258ce74446
[1] => 60dc4646-06ce-44d0-abe9-ee371847f4df
)
I need to search another object to find objects with the matching IDs, like below. Is there a way of doing this without a foreach? There are SEVERAL and I would like to not have to loop over the entire object every time.
stdClass Object
(
[id] => 1f422730-f54b-4e4d-9289-10258ce74446
[percentage] => 32
[destinations] => Array
(
[0] => stdClass Object
(
[id] => 59826
[destination_id] => 59826
[type] => Destination
[dequeue] =>
[value] => xxxxxxxxxxx
)
)
)
stdClass Object
(
[id] => 60dc4646-06ce-44d0-abe9-ee371847f4df
[percentage] => 68
[destinations] => Array
(
[0] => stdClass Object
(
[id] => 60046
[destination_id] => 60046
[type] => Destination
[dequeue] =>
[value] => xxxxxxxxxxxx
)
)
)
I need it to end up looking like this.
[376339] => Array
(
[0] => Array
(
[id] => 1f422730-f54b-4e4d-9289-10258ce74446
[percentage] => 32
[destinations] => Array
(
[0] => stdClass Object
(
[id] => 59826
[destination_id] => 59826
[type] => Destination
[dequeue] =>
[value] => xxxxxxxxxxx
)
)
)
[1] => Array
(
[id] => 60dc4646-06ce-44d0-abe9-ee371847f4df
[percentage] => 68
[destinations] => Array
(
[0] => stdClass Object
(
[id] => 60046
[destination_id] => 60046
[type] => Destination
[dequeue] =>
[value] => xxxxxxxxxxxx
)
)
)
)
I'm not sure if this makes any sense, that's why I had my two inital outputs I need to have merged into one somehow. This is all coming from one huge json object and I'm just using json_decode($jsonStuff) to decode it.
Would this be easier if I added true in the decode function? If I could just search for it like I could in python, that would be neat. But as it is, I'm at a loss as to how to get the output I need.
Note: Input json CANNOT be changed, I have no affiliation with the people that created it.
First loop over your input array and create an array with the key as the id
$input = json_decode($json_input);
$output = array();
foreach($input as $obj){
$output[$obj->id] = $obj;
}
then you can build your other array by searching the id on the array key
$massive_search_array = array(376339 => array
(
0 => 1f422730-f54b-4e4d-9289-10258ce74446,
1 => 60dc4646-06ce-44d0-abe9-ee371847f4df
)
);
$final_output = array();
foreach($massive_search_array as $index => $searches){
foreach($searches as $search){
if(isset($output[$search])){
$final_output[$index][] = $output[$search];
}
}
}

Get JSON value from PHP

All, I have got a JSON response from NEO4J:
Array
(
[columns] => Array
(
[0] => n
)
[data] => Array
(
[0] => Array
(
[0] => Array
(
[outgoing_relationships] => http://localhost:7474/db/data/node/1/relationships/out
[labels] => http://localhost:7474/db/data/node/1/labels
[data] => Array
(
[position] => Developer
[awesome] => 1
[name] => Michael
[children] => 3
)
[traverse] => http://localhost:7474/db/data/node/1/traverse/{returnType}
[all_typed_relationships] => http://localhost:7474/db/data/node/1/relationships/all/{-list|&|types}
[property] => http://localhost:7474/db/data/node/1/properties/{key}
[self] => http://localhost:7474/db/data/node/1
[properties] => http://localhost:7474/db/data/node/1/properties
[outgoing_typed_relationships] => http://localhost:7474/db/data/node/1/relationships/out/{-list|&|types}
[incoming_relationships] => http://localhost:7474/db/data/node/1/relationships/in
[extensions] => Array
(
)
[create_relationship] => http://localhost:7474/db/data/node/1/relationships
[paged_traverse] => http://localhost:7474/db/data/node/1/paged/traverse/{returnType}{?pageSize,leaseTime}
[all_relationships] => http://localhost:7474/db/data/node/1/relationships/all
[incoming_typed_relationships] => http://localhost:7474/db/data/node/1/relationships/in/{-list|&|types}
)
)
)
)
I do not know how to retrieve the value "position" under the data array, because the array is under another array.
Can you tell me how to do it with PHP?
Thx
Access them like this.
echo $yourarr['data'][0][0]['data']['position'];
Tips on how to locate :
Just locate where is the position keyword, Now look up to the array, As you can see the parent of position is data, think of how you reach from the start
(data)to the destination(position) (like a maze).
When you have more than 1 record try this
foreach($var['data'] as $inside){ //inner 1st stage
foreach($inside as $index => $main){ //inner 2nd stage
if($index == 'data'){ //check if index is data
echo $main['position']; //output position
}
}
}

Categories