parse PHP array - php

I have managed to get to the stage where I have an array that looks like this. Used (zend_json to decode a json response)
Array
(
[response] => Array
(
[status] => ok
[userTier] => free
[total] => 10
[startIndex] => 1
[pageSize] => 10
[currentPage] => 1
[pages] => 1
[results] => Array
(
[0] => Array
(
[id] => lifeandstyle/series/cycling
[type] => series
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/lifeandstyle/series/cycling
[apiUrl] => http://content.guardianapis.com/lifeandstyle/series/cycling
[sectionId] => lifeandstyle
[sectionName] => Life and style
)
[1] => Array
(
[id] => sport/cycling
[type] => keyword
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/sport/cycling
[apiUrl] => http://content.guardianapis.com/sport/cycling
[sectionId] => sport
[sectionName] => Sport
)
How would I go about parsing only the elements that are [webTitle] and [webUrl]
Thanks!

You can't specifically parse only those parts, but you can iterate over the results and access them.
foreach ($val['response']['results'] as $result) {
$title = $result['webTitle'];
$url = $result['webUrl'];
// ...
}

Related

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.

Parse XML to Array with SimpleXML

I've that xml structure retrieving from device
<packet>
<info action="fiscalmemory" fiscalmemorysize="1048576" recordsize="464" fiscal="1" uniqueno="ABC12345678" nip="123-456-78-90" maxrecordscount="2144" recordscount="7" maxreportscount="1830" reportscount="4" resetmaxcount="200" resetcount="0" taxratesprglimit="30" taxratesprg="1" currencychangeprglimit="4" currencychangeprg="0" fiscalstartdate="dd-mm-yyyy hh:dd:ss" fiscalstopdate="dd-mm-yyyy hh:dd:ss" currencyname="PLN" />
<ptu name="A" bres="Nobi">123.23</ptu>
<ptu name="B">123.23</ptu>
<ptu name="D">8</ptu>
<sale>999.23</sale>
</packet>
simpleXml does't see ptu's attributes
$array = simplexml_load_string($xml);
print_r($array);
It prints
SimpleXMLElement Object
(
[info] => SimpleXMLElement Object
(
[#attributes] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[ptu] => Array
(
[0] => 123.23
[1] => 123.23
[2] => 8
)
[sale] => 999.23
)
As we can see ptu doesn't contain attributes :/
I also tried parse it with recursive function because children also may contain chilren but without success :/
Could anybody point to me why SimpleXML doesn't take ptu's attributes and also share any parsing function?
Thanks in advance.
edited
As regards Nigel Ren I made that function
function parseXMLtoArray($xml){
$x = simplexml_load_string($xml);
$result = [];
function parse($xml, &$res){
$res['name'] = $xml->getName();
$res['value'] = $xml->__toString();
foreach ($xml->attributes() as $k => $v){
$res['attr'][$k] = $v->__toString();
}
foreach($xml->children() as $child){
parse($child, $res['children'][]);
}
}
parse($x, $result);
return $result;
}
$resArray = parseXMLtoArray($rawXml);
print_r($resArray);
this returns such array
Array
(
[name] => packet
[value] =>
[attr] => Array
(
[crc] => BKJFKHKD54
)
[children] => Array
(
[0] => Array
(
[name] => info
[value] =>
[attr] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[1] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => A
)
)
[2] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => B
)
)
[3] => Array
(
[name] => ptu
[value] => 8
[attr] => Array
(
[name] => D
)
)
[4] => Array
(
[name] => sale
[value] => 999.23
)
)
)
Is this correct?
Thanks again Nigel
When loading with SimpleXML, using print_r() gives only an idea of the content and doesn't have the full content. If you want to see the full content then use ->asXML()...
$array = simplexml_load_string($xml);
echo $array->asXML();
To check the attributes of <ptu> element, (this just gives the first one)...
echo $array->ptu[0]['name'];
This uses ->ptu to get the <ptu> element and takes the first one [0] and then takes the name attribute using ['name'].

PHP: Displaying data from Bigcommerce API

I am trying to display the data from Bigcommerce through php when I run the Bigcommerce::getCategories() i getting a array of data like this:
[0] => Bigcommerce\Api\Resources\Category Object
(
[ignoreOnCreate:protected] => Array
(
[0] => id
[1] => parent_category_list
)
[ignoreOnUpdate:protected] => Array
(
[0] => id
[1] => parent_category_list
)
[fields:protected] => stdClass Object
(
[id] => 88
[parent_id] => 0
[name] => Dell
[description] =>
[sort_order] => 0
[page_title] =>
[meta_keywords] =>
[meta_description] =>
[layout_file] =>
[parent_category_list] => Array
(
[0] => 88
)
[image_file] =>
[is_visible] => 1
[search_keywords] =>
[url] => /dell/
)
[id:protected] => 88
[ignoreIfZero:protected] => Array
(
)
[fieldMap:protected] => Array
(
)
)
but when I try to pass this to JQuery so that I can display it using this statement: <?php echo json_encode($categories); ?> I am getting an array of empty objects, what is the right way to get the array of objects in Bigcommerce API? Thanks.
From the first line of your code:
[0] => Bigcommerce\Api\Resources\Category Object
You have an object, not an array. Try casting it to an array first:
$array = (array) $yourObject;

Extract data from Array/Object in PHP?

First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}

Array inside array, only take incoming array

I have the following array structure, this is the array passed in to $response
Array
(
[inbox] => Array
(
[0] => Array
(
[location] => 3
[ID] => 8ba84195fe79a89af1a4b5bd8c280621
[smsc_number] => +44******
[sent] => 2013-02-25 14:57:20
[coding] => Default GSM alphabet (no compression)
[remote_number] => +447****
[status] => Read
[body] => Yeppp
)
)
[outbox] => Array
(
[0] => Array
(
[location] => 2
[ID] => d22c4368fadd64e98fab64acb6b8fa34
[reference_number] => 1
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => *****
[status] => Sent
[body] => Test
)
[1] => Array
(
[location] => 0
[ID] => f0c05e8dd2578d16d73bf5dbcf2ec3e6
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => 0****
[status] => UnSent
[body] => fdgg ddfgfdg fd
)
[2] => Array
(
[location] => 1
[ID] => d7537acb1b3994ecc11369bac46c4bb6
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => 0****3
[status] => UnSent
[body] => fdgg ddfgfdg fd
)
)
)
I'm only interested in the body of the inbox array. I thought I could just do two loops to get this, or just do $response[0] but it doesn't seem to work. Heres what I have:
$response = $sms->Get();
foreach ($response[0] as $value) {
foreach ($response as $value1) {
echo($value1['body']);
}
}
I'm obviously doing something very stupid - Any help would be really appreciated
Try this
foreach ($response['inbox'] as $inb) {
echo($inb['body']); }

Categories