Extract a value from a data structure to a variable - php

I need help in extracting "Duration" from the data structure below, to a variable called var_dur.
The data comes from: print_r($data);
Guzzle\Service\Resource\Model Object
(
[structure:protected] =>
[data:protected] => Array
(
[Job] => Array
(
[Arn] => arn:aws:elastictranscoder:us-west-2:98yufdos8u:job/fsdoiufds98u
[Id] => fdsu98sdufio
[Input] => Array
(
[AspectRatio] => auto
[Container] => auto
[FrameRate] => auto
[Interlaced] => auto
[Key] => iudyf98udsf
[Resolution] => auto
)
[Output] => Array
(
[AlbumArt] =>
[Composition] =>
[Duration] => 31
[Height] => 522
[Id] => 1
[Key] => dlsjf9ds8uf9d8sjuf9s.mp4
[PresetId] => sdufhy89dsfu98dsf
[Rotate] => 0
[SegmentDuration] =>
[Status] => Complete
[StatusDetail] =>
[ThumbnailPattern] => filename-700thumb-{resolution}-{count}
[Watermarks] => Array
(
)
[Width] => 640
)
[OutputKeyPrefix] =>
[Outputs] => Array
(
[0] => Array
(
[AlbumArt] =>
[Composition] =>
[Duration] => 31
[Height] => 522
[Id] => 1
[Key] => dlsjf9ds8uf9d8sjuf9s.mp4
[PresetId] => duisfy98dsuf89sd
[Rotate] => 0
[SegmentDuration] =>
[Status] => Complete
[StatusDetail] =>
[ThumbnailPattern] => filename-700thumb-{resolution}-{count}
[Watermarks] => Array
(
)
[Width] => 640
)
)
[PipelineId] => dsuf89dsuf89d
[Playlists] => Array
(
)
[Status] => Complete
)
)
)

Do something like this to iterate over the Array
function searchfor($text, $array) {
foreach (array_expression as $key => $val)
if($key == $text){
return $val
}
if(is_array($var){
return searchfor($text, $var);
}
}
return null;
}

Try it
$reflect = new ReflectionClass(OBJECT);
$props = $reflect->getProperties();
foreach ($props as $prop) {
print $prop->getName();
var_dump($prop->getValue());
}
About reflection class http://www.php.net/manual/en/reflectionclass.getproperties.php
About reflection property http://www.php.net/manual/en/class.reflectionproperty.php

Related

Convert object into normal multidimensional php array

I have a php variable $response containing an object with protected keys:
FindCompletedItemsResponse Object (
[searchResult:protected] => SearchResult Object (
[item:protected] => Array (
[0] => SearchItem Object (
[itemId:protected] => 383198481839
[title:protected] => Matchbox SCX SRS2 Jaguar "XJR-14" Super Racing Castrol #4 Slot Car 1/32 NIB
[globalId:protected] => EBAY-US
[primaryCategory:protected] => Category Object (
[categoryId:protected] => 4781
[categoryName:protected] => 1970-Now
)
[galleryURL:protected] => https://thumbs4.ebaystatic.com/m/mslyccjMA3BvwuDua4N-kkg/140.jpg
[viewItemURL:protected] => https://www.ebay.com/itm/Matchbox-SCX-SRS2-Jaguar-XJR-14-Super-Racing-Castrol-4-Slot-Car-1-32-NIB-/383198481839
[paymentMethod:protected] => Array ( [0] => PayPal )
[postalCode:protected] => 923**
[location:protected] => Fontana,CA,USA
[country:protected] => US
[shippingInfo:protected] => ShippingInfo Object (
[shippingServiceCost:protected] => Amount Object (
[attributeValues] => Array (
[currencyId] => USD
)
[value:protected] => 8.95
)
[shippingType:protected] => Flat
[shipToLocations:protected] => Array (
[0] => Worldwide
)
[expeditedShipping:protected] => 1
[handlingTime:protected] => 1
)
[sellingStatus:protected] => SellingStatus Object (
[currentPrice:protected] => Amount Object (
[attributeValues] => Array (
[currencyId] => USD
)
[value:protected] => 49.95
)
[convertedCurrentPrice:protected] => Amount Object (
[attributeValues] => Array (
[currencyId] => USD
)
[value:protected] => 49.95
)
[sellingState:protected] => EndedWithSales
)
[listingInfo:protected] => ListingInfo Object (
[startTime:protected] => 2019-10-07T18:28:15.000Z
[endTime:protected] => 2020-01-15T22:19:56.000Z
[listingType:protected] => StoreInventory
)
[returnsAccepted:protected] => 1
[condition:protected] => Condition Object (
[conditionId:protected] => 1000
[conditionDisplayName:protected] => New
)
)
)
[attributeValues] => Array (
[count] => 1
)
)
[paginationOutput:protected] => PaginationOutput Object (
[pageNumber:protected] => 1
[entriesPerPage:protected] => 100
[totalPages:protected] => 1
[totalEntries:protected] => 1
)
[ack:protected] => Success
[version:protected] => 1.13.0
[timestamp:protected] => 2020-04-09T10:01:15.148Z
)
I would like to convert this to a normal multidimensional php array where I can access e.g. the title like $response[0]["title"].
I tried get_object_vars($response) and json_decode(json_encode($response), true) but that is not doing anything when I am looking at the printed results.
and I tried this function:
function o2a($obj) {
if(!is_array($obj) && !is_object($obj)) return $obj;
if(is_object($obj)) $obj = get_object_vars($obj);
return array_map(__FUNCTION__, $obj);
}
but it just gives an empty array :(.
Thank you in advance for your help.

Flatten PHP stdClass object to array maintaining array dimensions

I am working with soap responses that contain nested wrappers and whose child(ren) have nested properties.
I am trying to flatten these response to:
remove the wrappers
flatten the children
maintain the individual children (dimensions)
I am currently working with the following that achieves #1 and #3 however it does not flatten the inner children. Note that $this->response is converted from a stdClass to Array before being flattened.
How can I also flatten down the inner nested child elements?
private function toArray()
{
$this->response = json_decode(json_encode($this->response), true);
return $this;
}
private function flatten($array = null)
{
if (is_null($array)) {
$array = $this->response;
}
if (is_array($array)) {
foreach ($array as $k => $v) {
if (count($v) == 1 && is_array($v)) {
return $this->flatten($v);
}
if (isset($v[0])) {
$this->response = $v;
return $this;
}
unset($this->response);
$this->response[] = $v;
return $this;
}
}
}
...which will transform this:
stdClass Object
(
[ArrayOfDevice] => stdClass Object
(
[Device] => Array
(
[0] => stdClass Object
(
[NamedElement] => stdClass Object
(
[Element] => stdClass Object
(
[ElementType] => DEVICE
[id] => Device1ID
)
[name] => Device1
)
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => stdClass Object
(
[NamedElement] => stdClass Object
(
[Element] => stdClass Object
(
[ElementType] => DEVICE
[id] => Device2ID
)
[name] => Device2
)
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
)
)
...to this:
Array
(
[0] => Array
(
[NamedElement] => Array
(
[Element] => Array
(
[ElementType] => DEVICE
[id] => Device1ID
)
[name] => Device1
)
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => Array
(
[NamedElement] => Array
(
[Element] => Array
(
[ElementType] => DEVICE
[id] => Device2ID
)
[name] => Device2
)
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
...but I'd prefer:
Array
(
[0] => Array
(
[ElementType] => DEVICE
[id] => Device1ID
[name] => Device1
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => Array
(
[ElementType] => DEVICE
[id] => Device2ID
[name] => Device2
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
...and in the case of a single item being returned, this:
stdClass Object
(
[ArrayOfAlarm] => stdClass Object
(
[Alarm] => stdClass Object
(
[Element] => stdClass Object
(
[ElementType] => ALARM
[id] => Alarm1ID
)
[activeTime] =>
[AlarmSeverity] =>
[AlarmState] =>
[description] =>
[deviceID] =>
[recommendedAction] =>
[resolvedTime] =>
[sensorID] =>
)
)
)
...to this:
Array
(
[0] => Array
(
[Element] => Array
(
[ElementType] => ALARM
[id] => Alarm1ID
)
[activeTime] =>
[AlarmSeverity] =>
[AlarmState] =>
[description] =>
[deviceID] =>
[recommendedAction] =>
[resolvedTime] =>
[sensorID] =>
)
)
...but I'd prefer:
Array
(
[0] => Array
(
[ElementType] => ALARM
[id] => Alarm1ID
[activeTime] =>
[AlarmSeverity] =>
[AlarmState] =>
[description] =>
[deviceID] =>
[recommendedAction] =>
[resolvedTime] =>
[sensorID] =>
)
)
You can flatten a single of your items with the following function:
function flatten_item($array)
{
$result = [];
foreach ($array as $k => $v) {
if (is_array($v)) {
$result = array_merge($result, $this->flatten_item($v));
} else {
$result[$k] = $v;
}
}
return $result;
}
When you have an array of results, you can pass this function as the callback to array_map. Only the relevant portion of the code:
if (isset($v[0])) {
$this->response = array_map([$this, 'flatten_item'], $v);
return $this;
}
// Convert single result to an array
$this->response = [$this->flatten_item($v)];
return $this;
Since the response (so far) always has the same structure, you could extract the payload without using recursion, which allows you to also remove the foreach in the flatten function:
function flatten()
{
// Remove outer wrappers [ArrayOfX][X] by extracting the value
$payload = current(current($this->response));
if (isset($payload[0])) {
$this->response = array_map([$this, 'flatten_item'], $payload);
} else {
$this->response = [$this->flatten_item($payload)];
}
return $this;
}
The function found here does just what you want, with a slight modification (commented out concatination of parent keys): https://gist.github.com/kohnmd/11197713#gistcomment-1895523
function flattenWithKeys(array $array, $childPrefix = '.', $root = '', $result = array()) {
foreach($array as $k => $v) {
if(is_array($v) || is_object($v)) $result = flattenWithKeys( (array) $v, $childPrefix, $root . $k . $childPrefix, $result);
else $result[ /*$root .*/ $k ] = $v;
}
return $result;
}
Letting $object equal your provided object, use as follows:
$array = json_decode(json_encode($object), true);
$result =[];
foreach( $array['ArrayOfDevice']['Device'] as $key => $value ){
$result[$key] = flattenWithKeys($value);
}
print_r($result);
Output:
Array
(
[0] => Array
(
[ElementType] => DEVICE
[id] => Device1ID
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => Array
(
[ElementType] => DEVICE
[id] => Device2ID
[name] => Device2
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location2
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
See it run here: http://sandbox.onlinephpfunctions.com/code/851e93389b993a0e44c1e916291dc444f47047d3

PHP Looping multi dim array

Array
(
[stat] => ok
[offset] => 0
[limit] => 50
[total] => 1
[monitors] => Array
(
[monitor] => Array
(
[0] => Array
(
[id] =>
[friendlyname] =>
[url] =>
[type] => 3
[subtype] =>
[keywordtype] =>
[keywordvalue] =>
[httpusername] =>
[httppassword] =>
[port] =>
[interval] => 300
[status] => 2
[alltimeuptimeratio] => 100
[log] => Array
(
[0] => Array
(
[type] => 2
[datetime] => 11/24/2016 04:01:32
)
[responsetime] => Array
(
[0] => Array
(
[datetime] => 12/09/2016 19:34:02
[value] => 109
)
[1] => Array
(
[datetime] => 12/09/2016 19:29:02
[value] => 110
)
[2] => Array
(
[datetime] => 12/09/2016 19:24:02
[value] => 110
)
)
)
)
)
)
I need to get the value of datetime, and value from the responsetime array. I tried the following but it seems to not return anything.
foreach($multidim as $value) {
foreach($value as $key => $val) {
if($key == "responsetime") {
echo $val[3];
}
}
}
Where $multidim is the large multi-dim array listed above. Any help is appreciated as I am not sure where to go from here.
Thank you in advance.
to access all the response times you should do sth like this
foreach($multidim['monitors']['monitor'][0]['responsetime'] as $key => $value) {
//here $key will be 0,1,2,3...
//$value['datetime'] will be 11/24/2016 04:01:32...
//$value['value'] will be 109,110,...
}
that is if you just want to access all the response times of the first monitor. if you want to access all the monitors and their response times you would need 2 loops for example
foreach($multidim['monitors']['monitor'] as $monitorId => $monitorData) {
foreach($monitorData['responsetime'] as $key => $value) {
//here you can access all the variables e.g
//$monitorId will be 0,1,2,3...
//$key will be 0,1,2,3...
//$value['datetime'] will be 11/24/2016 04:01:32...
//$value['value'] will be 109,110,...
}
}
I hope that sends you in the right direction :)

Update all values of PHP array having same index

This is my array structure:
Array
(
[0] => Array
(
[0] => Array
(
[topic_id] =>
[user_id] => ZGNjBQN9ac3K
[owner_id] => 15157
[tagged_field] => description
[created_date] => 2015-02-06 12:11:54
)
[1] => Array
(
[topic_id] =>
[user_id] => ZGNjAmD9ac3K
[owner_id] => 15157
[tagged_field] => description
[created_date] => 2015-02-06 12:11:54
)
)
)
I generate this structure before saving topics so i will get topic id only after this.
So in-order to save this array i need to set topic id to all index "topic_id"... lets say if topic_id is 11234 i need to updated all index with topic_id with value 11234.
Desired Output:
Array
(
[0] => Array
(
[0] => Array
(
[topic_id] => 11234
[user_id] => ZGNjBQN9ac3K
[owner_id] => 15157
[tagged_field] => description
[created_date] => 2015-02-06 12:11:54
)
[1] => Array
(
[topic_id] => 11234
[user_id] => ZGNjAmD9ac3K
[owner_id] => 15157
[tagged_field] => description
[created_date] => 2015-02-06 12:11:54
)
)
)
Try with -
$indexedArray = array();
foreach($yourArray as $value) {
foreach($value as $val) {
$indexedArray[$val['topic_id']][] = $val;
}
}
You need to use references in both foreach loops:
$arr = array(
array(
array("topic_id" => "", "user_id" => "ZGNjBQN9ac3K", "owner_id" => "15157", "tagged_field" => "description", "created_date" => "2015-02-06 12:11:54"),
array("topic_id" => "", "user_id" => "ZGNjBQN9ac3K", "owner_id" => "15157", "tagged_field" => "description", "created_date" => "2015-02-06 12:11:54"),
)
);
foreach($arr as &$value) {
foreach($value as &$val) {
$val['topic_id'] = $newvalue;
}
}
print_r($arr);
You can do by simple way using reference variable like
$yourArray = array(array(array("topic_id"=>"","user_id"=>110),array("topic_id"=>"","user_id"=>786)));
foreach($yourArray as &$value) {
foreach($value as &$val) {
$val['topic_id'] = "your_topic_id";
}
}
Output
Array
(
[0] => Array
(
[0] => Array
(
[topic_id] => your_topic_id
[user_id] => 110
)
[1] => Array
(
[topic_id] => your_topic_id
[user_id] => 786
)
)
)

Find a value in nested associative array

I want to get the value of 'GUID' with the value of 'SamAccountName'. i.e. I only have the value pf 'SamAccountName' and I would like to get the value of 'GUID' for that part of the array.
Array
(
[0] => Array
(
[DistinguishedName] => CN=johnn#playgroundla,OU=playgroundla,OU=Hosting,DC=exch024,DC=domain,DC=local
[GUID] => 26d7c204-7db7-4601-8cd2-0dd0d3b37d97
[OriginatingServer] => dcprov024-CA-1.exch024.domain.local
[Name] => johnn#playgroundla
[HostingObjectType] => Array
(
[HostingObjectTypes] => Array
(
[0] => ActiveSync
[1] => MSExchange2007Mailbox
[2] => ActiveDirectoryUser
)
)
[HostingOwners] => Array
(
[HostingObjectOwners] => Array
(
[0] => MSExchange2007Mailboxes
[1] => ActiveDirectoryUsers
)
)
[Attributes] => Array
(
[Hidden] =>
[ReadOnly] =>
[SpecialAccess] =>
[Items] => Array
(
)
)
[DisplayName] => John Nolan
[SamAccountName] => johnn_playgroundla
[FullSamAccountName] => EXCH024\johnn_playgroundla
[UserPrincipalName] => johnn#playgroundla.com
[AccountExpires] =>
[Enabled] =>
[EnabledFeatures] => Array
(
[string] => Array
(
[0] => ActiveSync
[1] => MSExchangeMailboxes
[2] => ActiveDirectoryUsers
)
)
[LastLogonTimestamp] =>
)
[1] => Array
(
[DistinguishedName] => CN=csliney#playgroundla,OU=playgroundla,OU=Hosting,DC=exch024,DC=domain,DC=local
[GUID] => 71224be8-1b8b-46e7-97ef-2cd873bf9b7f
[OriginatingServer] => dcprov024-CA-1.exch024.domain.local
[Name] => csliney#playgroundla
[HostingObjectType] => Array
(
[HostingObjectTypes] => Array
(
[0] => ActiveSync
[1] => MSExchange2007Mailbox
[2] => ActiveDirectoryUser
)
)
[HostingOwners] => Array
(
[HostingObjectOwners] => Array
(
[0] => MSExchange2007Mailboxes
[1] => ActiveDirectoryUsers
)
)
[Attributes] => Array
(
[Hidden] =>
[ReadOnly] =>
[SpecialAccess] =>
[Items] => Array
(
)
)
[DisplayName] => Christopher Sliney
[SamAccountName] => csliney_playgroundla
[FullSamAccountName] => EXCH024\csliney_playgroundla
[UserPrincipalName] => csliney#playgroundla.com
[AccountExpires] =>
[Enabled] =>
[EnabledFeatures] => Array
(
[string] => Array
(
[0] => ActiveSync
[1] => MSExchangeMailboxes
[2] => ActiveDirectoryUsers
)
)
[LastLogonTimestamp] =>
)
[2] => Array
(
[DistinguishedName] => CN=lee#playgroundla,OU=playgroundla,OU=Hosting,DC=exch024,DC=domain,DC=local
[GUID] => b428b57f-4cd4-4243-a76a-f25f5ff3be97
[OriginatingServer] => dcprov024-CA-1.exch024.domain.local
[Name] => lee#playgroundla
[HostingObjectType] => Array
(
[HostingObjectTypes] => Array
(
[0] => MSExchange2007Mailbox
[1] => ActiveDirectoryUser
)
)
[HostingOwners] => Array
(
[HostingObjectOwners] => Array
(
[0] => MSExchange2007Mailboxes
[1] => ActiveDirectoryUsers
)
)
[Attributes] => Array
(
[Hidden] =>
[ReadOnly] =>
[SpecialAccess] =>
[Items] => Array
(
)
)
[DisplayName] => Lee Roderick
[SamAccountName] => lee_playgroundla
[FullSamAccountName] => EXCH024\lee_playgroundla
[UserPrincipalName] => lee#playgroundla.com
[AccountExpires] =>
[Enabled] =>
[EnabledFeatures] => Array
(
[string] => Array
(
[0] => MSExchangeMailboxes
[1] => ActiveDirectoryUsers
)
)
[LastLogonTimestamp] =>
)
[3] => Array
(
[DistinguishedName] => CN=theresa#playgroundla,OU=playgroundla,OU=Hosting,DC=exch024,DC=domain,DC=local
[GUID] => 4b2aee17-9e88-4de9-b95b-63a9877835a6
[OriginatingServer] => dcprov024-CA-1.exch024.domain.local
[Name] => theresa#playgroundla
[HostingObjectType] => Array
(
[HostingObjectTypes] => Array
(
[0] => ActiveSync
[1] => MSExchange2007Mailbox
[2] => ActiveDirectoryUser
)
)
[HostingOwners] => Array
(
[HostingObjectOwners] => Array
(
[0] => MSExchange2007Mailboxes
[1] => ActiveDirectoryUsers
)
)
[Attributes] => Array
(
[Hidden] =>
[ReadOnly] =>
[SpecialAccess] =>
[Items] => Array
(
)
)
[DisplayName] => Theresa Baker
[SamAccountName] => theresa_playgroundla
[FullSamAccountName] => EXCH024\theresa_playgroundla
[UserPrincipalName] => theresa#playgroundla.com
[AccountExpires] =>
[Enabled] =>
[EnabledFeatures] => Array
(
[string] => Array
(
[0] => ActiveSync
[1] => MSExchangeMailboxes
[2] => ActiveDirectoryUsers
)
)
[LastLogonTimestamp] =>
)
)
This was originally a stdClass object but I used json_decode(json_encode($obj), true) to convert to an associative array.
Sounds like you want to get the GUID portion for the value of 'SamAccountName'. Use a foreach loop:
function getGUID($san, $array) {
foreach($array as $a) {
if($a['SamAccountName'] == $san) {
return $a['GUID'];
}
}
return false;
}
$guid = getGUID("SamAccountNameHere", $yourArray);
You can use a simple loop to fetch it
$id = 0;
foreach($data as $item) {
if (isset($item['SamAccountName']) && 'accountName' == $item['SamAccountName']) {
$id = $item['GUID'];
break;
}
}
var_dump($id);
is this what you are looking for?
function findBySam($arrayList, $sam) {
foreach($arrayList as $array) {
if($array['SamAccountName'] == $sam) {
return $array;
}
}
return false;
}
Here is an example of a function that you could use. This assumes that there will be only one object with the SamAccountName that you supply in the array (it just uses the first one that it finds). It returns the GUID of the matching array and false if it cannot find an array with a matching SamAccountName.
function getGuidForSamAccountName($arr, $name) {
foreach ($arr as $elem) {
if ($elem['SamAccountName'] === $name) {
return $elem['GUID'];
}
}
return false; //No match found
}
You can use array_filter function of php:
http://php.net/manual/en/function.array-filter.php
example:
$GUID = "sample";
array_filter($array, "findElement");
function findElement($el) {
return $el["GUID"] == $_GLOBAL["GUID"];
}
Not a very elegant solution... but it should work.

Categories