how to get individual values from this array - php

I got this result when I printed the array print_r($post);
Array ( [0] => Array ( [0] => stdClass Object ( [subscriber_id] => 80010055 [cto_id] => [name] => n [mobile] => 1234564444 [state] => [city] => fsd [cto_subscriber_id] => 0 [password] => e10adc3949ba59abbe56e057f20f883e [email] => n#n.com [email_verified] => 1 [ip_address] => ::1 [last_login_time] => 2012-10-24 11:37:19 ) ) [1] => Array ( [0] => stdClass Object ( [subscriber_id] => 80010055 [ip_address] => [landline_number] => [sex] => 0 [dob] => 0000-00-00 00:00:00 [marital_status] => hfg [state] => [addres] => fgh [city] => fghfg [pincode] => fghfgh ) ) )
How can I get single values

Typecast it to array?
$arr = (array)$post[0][0];
And then you'll be able to loop through it as through normal array
foreach ($arr as $key => $value){....}

foreach $post as $sub {
foreach $sub as $single {
echo $single;
}
}

Think you should learn the basics of arrays and objects first.
Anyway in order to get the value of lets say subscriber_id you should use the following:
$post[0][0]->subscriber_id
First you get into the array and then get the value out of the Object

Related

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'].

Access data inside stdObject

I have stdClass data after submitting the form:
"Array
(
[0] => stdClass Object
(
[username] => stdClass Object
(
[0] => 1001037
[1] => AARONJAMES
[2] => 1
[3] => ULTIMA (Red)
[4] => 1001037|1
[staff_id] => 1001037
[username] => AARONJAMES
[fkhouseid] => 1
[hname] => ULTIMA (Red)
[id] => 1001037|1
[$$hashKey] => object:13
)
[$$hashKey] => object:6
[points] => 50
)
[1] => stdClass Object
(
[username] => stdClass Object
(
[0] => 1001075
[1] => AARONKOH
[2] => 2
[3] => NACHOZZ (Purple)
[4] => 1001075|2
[staff_id] => 1001075
[username] => AARONKOH
[fkhouseid] => 2
[hname] => NACHOZZ (Purple)
[id] => 1001075|2
[$$hashKey] => object:14
)
[house] =>
[points] => 20
[$$hashKey] => object:306
)
)"
I want to access id variable inside username array to explode it later and insert data into database.
I tried to use to access it but it didnt work:
foreach ($persons as $key => $object) {
var_dump($persons[$key]->id);
}
How can I access id variable inside username?
Assuming $persons have array. You can try like below.
foreach ($persons as $key => $object) {
var_dump($object->username->id);
}
As per my comments you should try this
foreach ($persons as $key => $object) {
echo $object[$key]->username->id;
}
some details about array
$key is the index number of person array.
username is the stdClass Object so you can get like this ->username.

Add mysql row to existing array

I have an existing array, and I want to add some items in it from a mysql row
$extendedadmindetails = full_query("SELECT * FROM `tbladmins` WHERE `id`='{$_SESSION['adminid']}'");
$extendedadmindetailsrow = mysql_fetch_assoc ($extendedadmindetails);
array_push($apiresults, $extendedadmindetailsrow);
This returns an array in an array:
Array
(
[result] => success
[adminid] => 1
[name] => My Name
[notes] =>
[signature] =>
[allowedpermissions] => My Name
[departments] => 1
[requesttime] => 2017-02-26 12:44:06
[0] => Array
(
[id] => 1
[uuid] => sqdqsdqsdqsdq454
[roleid] => 1
[username] => Myname
[password] => $dfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdf
[passwordhash] => $jghjghjghjghjghjghjghjghjg
[updated_at] => 0000-00-00 00:00:00
)
)
while I need:
Array
(
[result] => success
[adminid] => 1
[name] => My Name
[notes] =>
[signature] =>
[allowedpermissions] => My Name
[departments] => 1
[requesttime] => 2017-02-26 12:44:06
[id] => 1
[uuid] => sqdqsdqsdqsdq454
[roleid] => 1
[username] => Myname
[password] => $dfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdf
[passwordhash] => $jghjghjghjghjghjghjghjghjg
[updated_at] => 0000-00-00 00:00:00
)
I believe I should use array_push to add to an existing array, but I'm not sure how to proceed from there. Do I need to loop trough the extendedadmindetailsrow array and add items 1 by 1?
Any one can help me out with this?
Thanks!!
use of array_merge is better in case
// Considering your mysql is returning only 1 row
foreach ($extendedadmindetailsrow as $key => $row) {
$arr = $row;
}
// after this if you will try array_push also that will work
$result = array_merge($apiresults, $arr);
print_r($result);
Take a look at array_merge
array_merge($apiresults, $extendedadmindetailsrow);
You can:
$result = $apiresults + $extendedadmindetailsrow;
Use array_merge()
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
Output will be
Array (
[0] => red
[1] => green
[2] => blue
[3] => yellow
)

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

segregating php object variables

I have some XML that is being returned to be as an object, like this:
SwitchvoxResponse Object
(
[apiStatus:private] => success
[apiErrors:private] => Array
(
)
[apiResult:private] => Array
(
[calls] => Array
(
[page_number] => 1
[total_pages] => 1
[items_per_page] => 50
[total_items] => 1
[call] => Array
(
[0] => Array
(
[id] => 14301
[origination] => outgoing
[start_time] => 2011-06-17 13:40:58
[from] => CALLER_NAME <4485>
[from_account_id] => 1120
[from_name] => CALLER_NAME
[from_number] => 4485
[to] => CALLEE_NAME <6534>
[to_account_id] => 1101
[to_name] => CALLEE_NAME
[to_number] => 6534
[total_duration] => 47
[talk_duration] => 43
[events] => Array
(
[event] => Array
(
[0] => Array
(
[start_time] => 2011-06-17 13:40:58
[type] => OUTGOING
[display] => Dialed number (6534)
)
[1] => Array
(
[start_time] => 2011-06-17 13:40:58
[type] => INTERNAL
[display] => Rang CALLEE_NAME <6534>
)
[2] => Array
(
[start_time] => 2011-06-17 13:41:02
[type] => TALKING
[display] => Talked to CALLEE_NAME <6534> for 43 seconds
)
[3] => Array
(
[start_time] => 2011-06-17 13:41:45
[type] => HANGUP
[display] => Call was hung up by CALLER_NAME <4485>
)
)
)
)
)
)
)
)
How do I pull out the values of these variables?
The results can be accessed via the SwitchvoxResponse::getResult() method. Given $object is the SwitchvoxResponse object quoted in the question, the example below loops over each call and prints the from values.
$result = $object->getResult();
foreach ($result['calls']['call'] as $call) {
echo $call['from'];
}
Similarly, the response status is fetched via $object->getResponseStatus() and any errors via $object->getErrors().
The response statuses can be one of SV_RESPONSE_SUCCESS, SV_RESPONSE_FAULT or SV_RESPONSE_FAILED.
Edit re. comments
To get the items for the first call only, simply do:
$result = $object->getResult();
$call = $result['calls']['call'][0];
// And access the values like
echo $call['from_name'];
All three properties are marked private, so they would have to be obtained through accessor methods marked public

Categories