PHP array output specific key and/or value - php

I want to grab specific values based on keys in my PHP array.
I am getting a whole bunch of unwanted syntax.
I am using this library for API calls to a Insightly CRM https://github.com/Insightly/insightly-php
Code:
<!DOCTYPE html>
<html>
<head>
<?php
echo "<h1>PHP Insightly Test</h1>";
require("insightly.php");
$i = new Insightly('apikey');
$contacts = $i->getContacts();
?>
<title></title>
</head>
<body>
<?php
$array = array();
foreach ($contacts as $contact)
{
$array[] = $contact;
}
print_r($array[1]);
?>
</body>
</html>
Webpage output as follows:
stdClass Object ( [CONTACT_ID] => 1234567 [SALUTATION] => [FIRST_NAME] => Frank [LAST_NAME] => Foster [BACKGROUND] => [IMAGE_URL] => http://dfvd [DEFAULT_LINKED_ORGANISATION] => [OWNER_USER_ID] => 343435 [DATE_CREATED_UTC] => 2015-11-22 21:46:25 [DATE_UPDATED_UTC] => 2015-11-22 21:52:19 [VISIBLE_TO] => EVERYONE [VISIBLE_TEAM_ID] => [VISIBLE_USER_IDS] => [CUSTOMFIELDS] => Array ( ) [ADDRESSES] => Array ( ) [CONTACTINFOS] => Array ( [0] => stdClass Object ( [CONTACT_INFO_ID] => 34353453 [TYPE] => EMAIL [SUBTYPE] => [LABEL] => Work [DETAIL] => email#email.com ) ) [DATES] => Array ( ) [TAGS] => Array ( ) [LINKS] => Array ( ) [CONTACTLINKS] => Array ( ) [EMAILLINKS] => Array ( ) )
I require individual values
e.g (first name / last name) - Frank Foster
I tried print_r($array[1]['FIRST_NAME']);? but had no luck. Wondering if I need to encode or decode? Unsure the answer to this.
Thanks.

You can echo FIRST_NAME using this Syntax:
echo $array[1]->FIRST_NAME;

Use should use "->" to access object properties.
print_r($array[1]->FIRST_NAME);

Related

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

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

How to get value out of this...?

Can someone explain me how to get data out of this...like if I just want subject, description..etc...
stdClass Object
(
[tickets] => Array
(
[0] => stdClass Object
(
[url] => https://codemymobilecom.zendesk.com/api/v2/tickets/1.json
[id] => 1
[external_id] =>
[via] => stdClass Object
(
[channel] => sample_ticket
[source] => stdClass Object
(
[from] => stdClass Object
(
)
[to] => stdClass Object
(
)
[rel] =>
)
)
[created_at] => 2015-04-22T08:30:29Z
[updated_at] => 2015-05-19T06:01:22Z
[type] => incident
[subject] => This is a sample ticket requested and submitted by you
[raw_subject] => This is a sample ticket requested and submitted by you
[description] => This is the first comment. Feel free to delete this sample ticket.
[priority] => high
[status] => closed
[recipient] =>
[requester_id] => 794599791
[submitter_id] => 794599791
[assignee_id] => 794599791
[organization_id] => 39742491
[group_id] => 24344491
[collaborator_ids] => Array
(
)
[forum_topic_id] =>
[problem_id] =>
[has_incidents] =>
[due_at] =>
[tags] => Array
(
[0] => sample
[1] => zendesk
)
[custom_fields] => Array
(
)
[satisfaction_rating] =>
[sharing_agreement_ids] => Array
(
)
[fields] => Array
(
)
[followup_ids] => Array
(
)
[brand_id] => 565681
)
[1] => stdClass Object
(
[url] => https://codemymobilecom.zendesk.com/api/v2/tickets/10.json
[id] => 10 //multiple object like [0]...
Thanks...Any help would be great..
When you need to access to array's key, use []. When you have object, use ->.
echo $obj->tickets[0]->subject; // returns first subject
echo $obj->tickets[0]->description; // returns first description
You can put it into foreach loop, of course to gain all subjects, etc.
It's STD object so use properties
$obj->tickets[0]->subject
$obj->tickets[0]->description
You can obviously loop tickets
foreach($obj->tickets as $ticket)
{
echo $ticket->subject;
echo $ticket->description
}
this is an std object.to get subject and description follow this
$obj->tickets[0]->subject;
$obj->tickets[0]->description;
if you feel better in array just make it array using this code
$array = get_object_vars($obj);

trying to access json results in php

Im trying to display some data im receiving from the cloudstack API. I can display some of the data I want when I use the JSON as objects, with the following code;
stdClass Object
(
[listvirtualmachinesresponse] => stdClass Object
(
[count] => 2
[virtualmachine] => Array
(
[0] => stdClass Object
(
[id] => bab03c9b-94e0-429f-906c-8853de306e9a
[name] => LinuxL1
[displayname] => LinuxL1
[account] => admin
[domainid] => a3121682-837b-11e3-964c-001372f94016
[domain] => ROOT
[created] => 2014-05-08T13:43:01+0200
[state] => Running
[haenable] =>
[zoneid] => 7a3ee2f0-540a-4232-8264-50a47a91001d
[zonename] => Amsterdam
[hostid] => 024b9ca2-4076-488e-ad13-86dfb7f2b766
[hostname] => ptvirt6
[templateid] => cf6abb42-574f-4840-886a-8662c5914166
[templatename] => CentOS 6.5
[templatedisplaytext] => good
[passwordenabled] =>
[isoid] => cf6abb42-574f-4840-886a-8662c5914166
[isoname] => CentOS 6.5
[isodisplaytext] => good
[serviceofferingid] => 4fc30c59-4600-44ed-b0bb-7fc48e795d90
[serviceofferingname] => L1
[cpunumber] => 1
[cpuspeed] => 1000
[memory] => 1024
[cpuused] => 0.02%
[networkkbsread] => 55
[networkkbswrite] => 1
[diskkbsread] => 1000680
[diskkbswrite] => 1301501
[diskioread] => 77192
[diskiowrite] => 8884
[guestosid] => a92508f4-837b-11e3-964c-001372f94016
[rootdeviceid] => 0
[rootdevicetype] => ROOT
[securitygroup] => Array
(
[0] => stdClass Object
(
[id] => edfe848c-837b-11e3-964c-001372f94016
[name] => default
[description] => Default Security Group
[account] => admin
[ingressrule] => Array
(
)
[egressrule] => Array
(
)
[tags] => Array
(
)
)
)
[nic] => Array
(
[0] => stdClass Object
(
[id] => bfaeb76d-7b5a-46b1-aaa7-7dd15e86bf2e
[networkid] => 83007a42-e4b7-4ea2-aa21- 20938ea3bc56
[networkname] => defaultGuestNetwork
[netmask] => 111.111.111.111
[gateway] => 111.111.111.111
[ipaddress] => 111.111.111.111
[isolationuri] => ec2://untagged
[broadcasturi] => vlan://untagged
[traffictype] => Guest
[type] => Shared
[isdefault] => 1
[macaddress] => 06:a5:24:00:00:0a
)
)
[hypervisor] => KVM
[instancename] => i-2-9-VM
[tags] => Array
(
)
[affinitygroup] => Array
(
)
[displayvm] => 1
[isdynamicallyscalable] =>
)
I can read the name / state from the list with a foreach loop
<?php
$api_content = file_get_contents("http://127.0.0.1:5950/client/api?command=listVirtualMachines&domainid=1&account=admin&response=json");
$api_data = json_decode($api_content);
$ap_machine = $api_data->listvirtualmachinesresponse->virtualmachine;
echo "<pre>";
print_r($api_data);
echo "</pre>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table border="1" width="300">
<tr>
<td>Naam</td>
<td>Status</td>
<td>Ip Address</td>
<td>Health</td>
</tr>
<?php
echo "<tr>";
foreach($ap_machine as $item){
echo "<td>".$item->name."</td>";
echo "<td>".$item->state."</td>";
echo "<td>".$item->nic->ipaddress."</td>";
if($item->state == 'Running'){
echo '<td><img src="/600px-Approve_icon.svg.png" height="50" width="50"> </td>';
}
else{
echo '<td><img src="/fail.png" height="25" width="25"></td>';
}
echo "</tr>";
}
?>
I've read online to make an associative array from the json list, I did that aswell and didnt get a result.
In your PHP code you are accessing nice key as a normal element of json:
echo "<td>".$item->nic->ipaddress."</td>";
But, from your var_dump output I can see its of array type.
So, to access elements of nice array, you'l have to access it by specifying array index.
echo "<td>".$item->nic[0]->ipaddress."</td>";
Look dude
change
$api_data = json_decode($api_content);
to
$api_data = json_decode($api_content, TRUE);
this makes it an associative array
check http://www.php.net/manual/en/function.json-decode.php

how to fetch this array using foreach loop

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();
}

Categories