i have a multidimensional array. the array is returned by parsing xml using curl. when curl gave me the output i converted the output into array using $array = (array) simplexml_load_string($query); and the $array is given below. Now i want to fetch this array using foreach loop and want everything from this array
Array
(
[Meta] => SimpleXMLElement Object
(
[Query] => php programming
[ResultOffset] => SimpleXMLElement Object
(
)
[NumResults] => 25
[TotalResults] => 36839
)
[Slideshow] => Array
(
[0] => SimpleXMLElement Object
(
[ID] => 1966058
[Title] => title here
[Description] => description here
[Status] => 2
[Username] =>usrname
[URL] => url here
[ThumbnailURL] => a url
[ThumbnailSmallURL] => a url
[Embed] => some embed code
)
[1] => SimpleXMLElement Object
(
[ID] => 1966058
[Title] => title here
[Description] => description here
[Status] => 2
[Username] =>usrname
[URL] => url here
[ThumbnailURL] => a url
[ThumbnailSmallURL] => a url
[Embed] => some embed code
)
and continue
You can retrieve meta information without using foreach:
echo $array['Meta']->Query;
echo $array['Meta']->NumResults;
and so on...
To fetch slideshows:
foreach($array['Slideshow'] as $slideshow)
{
echo $slideshow->ID;
echo $slideshow->Title;
//-- and so on...
}
If you want to retrieve the ID and Titles of each SimpleXMLElement Object, try this:
<?php
forach ($array['Slideshow'] as $simpleXMLelem) {
echo $simpleXMLelem->getId();
echo $simpleXMLelem->getTitle();
}
Related
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
Am trying to come up with a code to search for a string in an array of objects, if string is found, get values of the submenus object. Like if the string "main/dashboard" is found then get submenus
stdClass Object
(
[type] => single
[slug] => view_admin_dashboard
[menus] => stdClass Object
(
[label] => Dashboard
[icon] => dashboard
[url] => main/dashboard
)
[submenus] => Array
(
[0] => stdClass Object
(
[submenu_slug] => view_all_users
[label] => View all Users
[icon] => users
[url] => main/users/all
)
[1] => stdClass Object
(
[submenu_slug] => delete_users
[label] => Delete Users
[icon] => users
[url] => main/user/delete
)
)
)
I have this for now but its giving me error in_array expects parameter 2 to be array;
foreach($mainarray as $menus => $menu){
if(in_array("main/dashboard",$menu)){
foreach($menu as $submenu){
echo $submenu->url;
}
}
}
Maybe you want something like this:
foreach($mainarray as $menu){
if($menu->menus->url == "main/dashboard"){ // if found the url in the object
foreach($menu->submenus as $submenu)
echo $submenu->url;
}
}
}
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'];
// ...
}
How would I access the [0] -> Array() located below and retrieve the [title] which is "Spirited Away" by iterating over the array?
Array
(
[#attributes] => Array
(
[version] => 2.0
)
[channel] => Array
(
[title] => Site Title
[link] => site/
[language] => en-us
[category] => All
[image] => Array
(
[title] => Site
[url] => http://example.com
[link] => example.com
)
[item] => Array
(
[0] => Array
(
[title] => Spirited Away
[pubDate] => date
[category] => Movies
[link] => linkhere
[enclosure] => Array
(
[#attributes] => Array
(
[url] => someurlhere
[length] => length
[type] => application/x-bittorrent
)
)
I'm currently trying to iterate over the array using a foreach loop but It's outputting nothing. I would post my code but the code section of this question is already too long. I'm using PHP and nothing I have tried so far was working.
This JSON code was generated from an XML document using json_encode and then decoded using json_decode into a JSON object.
comment to answer as its correct.
to loop through this particular array structure its:
foreach ( $array['channel']['item'] as $x){
echo $x['title'];
}
I'm using the CloudFusion class to get Amazon.com data and my code is simple:
$items = $pas->item_search( "shoes", array(
"ResponseGroup" => "Small",
"SearchIndex" => "Blended" ));
$items = $items->body->Items;
echo "<pre>";
print_r( $items );
echo "</pre>";
This returns the following:
SimpleXMLElement Object (
[Request] => SimpleXMLElement Object
(
[IsValid] => True
[ItemSearchRequest] => SimpleXMLElement Object
(
[Keywords] => shoes
[ResponseGroup] => Small
[SearchIndex] => Blended
)
)
[TotalResults] => 737435
[TotalPages] => 245816
[SearchResultsMap] => SimpleXMLElement Object
(
[SearchIndex] => Array
(
[0] => SimpleXMLElement Object
(
[IndexName] => Kitchen
....
)
[Item] => Array
(
[0] => SimpleXMLElement Object
(
[ASIN] => B0001Z95QY
[DetailPageURL] => http://www.amazon.com/Household-Essentials-MS6030-Seasonal-Storage/dp/B0001Z95QY%3FSubscriptionId%3D0WASFFPR5B82TH4ZQB82%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB0001Z95QY
[ItemLinks] => SimpleXMLElement Object
(
[ItemLink] => Array
(
[0] => SimpleXMLElement Object
(
[Description] => Technical Details
[URL] => http://www.amazon.com/Household-Essentials-MS6030-Seasonal-Storage/dp/tech-data/B0001Z95QY%3FSubscriptionId%3D0WASFFPR5B82TH4ZQB82%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0001Z95QY
) ....................
)
[1] => SimpleXMLElement Object
(
[ASIN] => B001ACNBZ8
[DetailPageURL] => http://www.amazon.com/Peet-Shoe-Dryer-Boot-Original/dp/B001ACNBZ8%3FSubscriptionId%3D0WASFFPR5B82TH4ZQB82%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB001ACNBZ8
[ItemLinks] => SimpleXMLElement Object
(...................
)
)
What I'd like to do is get down to the "Item" level, then run a foreach to get each individual entry. I tried $items = $items->Item, but this returns only the first entry.
Any ideas?
First of all, you should avoid using print_r() on SimpleXMLElement, instead just take a look at the XML using asXML(). That's also what you should post here, instead of print_r()'s output.
I can't decipher the code you have posted so I'll take a wild guess and suggest that you try something like:
foreach ($items->body->Items->Item as $Item)
{
}
At any rate, if you want to iterate over something, foreach is the answer.