I have convert my object data to an array and now i am trying to extract certain parts from the multi dimensional array however i am having some problems. Assistance is appreciated, thank you.
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/89647580016/feed'
);
$response = $request->execute();
$graphObject = $response->getGraphObject()->AsArray();
/* handle the result */
// print data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
The following is the output:
Array
(
[data] => Array
(
[0] => stdClass Object
(
[id] => 89647580016_10153019927930017
[from] => stdClass Object
(
[name] => Central Casting Los Angeles
[category] => Local Business
[category_list] => Array
(
[0] => stdClass Object
(
[id] => 176831012360626
[name] => Professional Services
)
)
[id] => 89647580016
)
[message] => ***NON Union Submissions***
Must be registered with Central Casting!
Jessica is currently booking a TV show working tomorrow Friday June 26th with a possible recall Monday June 29th in LA. These will be Night Calls, so you must be okay working late into the night.
She is looking for Caucasian looking men, who appear to be in their 30's-50's, who appear to be very upscale, who have business suits.
If this is you please call submission line 818-260-3952. Thank you!
[actions] => Array
(
[0] => stdClass Object
(
[name] => Comment
[link] => https://www.facebook.com/89647580016/posts/10153019927930017
)
[1] => stdClass Object
(
[name] => Like
[link] => https://www.facebook.com/89647580016/posts/10153019927930017
)
[2] => stdClass Object
(
[name] => Share
[link] => https://www.facebook.com/89647580016/posts/10153019927930017
)
)
How can i print all the ['message'] ? I tried:
foreach ($graphObject as $key => $value) {
echo '<br>'.$key['message'];
}
But i got a error. Thank you for your help.
Your array has some keys which elements are actually StdClass. You can't reffer to it as $key['message'] but as: $key->message.
Also, don't forget to include your error message. An error is extremely generic and we can't/won't help you if there is no indication of what is wrong.
I didn't notice your foreach. As you are iterating only on $graphObject first level, you will get as $key data and as value another whole array which each key has a StdClass. On your foreach, run it as foreach ($graphObject['data'] as $key => $value) , then use it as echo $value->message
Related
Having real issues with this. I want to be able to get a value from this data which is returned via an API.
ie get value by
$CM_user_customfields['Organisation'],
$CM_user_customfields->Organisation.
is that even possible? I have tried loops and rebuilding the array but i always end up with a similar results and perhaps overthinking it.
I can't use the [int] => as the number of custom fields will be changing a lot.
$CM_user_customfields = $CM_details->response->CustomFields ;
echo '<pre>' . print_r( $CM_user_customfields, true ) . '</pre>';
// returns
Array
(
[0] => stdClass Object
(
[Key] => Job Title
[Value] => Designer / developer
)
[1] => stdClass Object
(
[Key] => Organisation
[Value] => Jynk
)
[2] => stdClass Object
(
[Key] => liasoncontact
[Value] => Yes
)
[3] => stdClass Object
...
many thanks, D.
I recommend convert to associative array first:
foreach($CM_user_customfields as $e) {
$arr[$e->Key] = $e->Value;
}
Now you can access it as:
echo $arr['Organisation'];
You can also achieve it by: (PHP 7 can convert stdClass and will do the trick)
$arr = array_combine(array_column($CM_user_customfields, "Key"), array_column($CM_user_customfields, "Value")));
I have a SOAP Response from a Web Service and have extracted the XML data as a SimpleXMLElement. I have then iterated through this object to extract the various fields I need and save them into an array, which becomes an array of SimpleXMLElement objects.
I am now trying to export this data into a MySQL Database which, according to my research, means turning the array into a String and then using mysql_query("INSERT INTO (whatever) VALUES (whatever)");. I have tried implode and serialize but neither work and I get the error:
Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'
This is what the array I have created from the SimpleXMLELement looks like:
Array
(
[0] => Array
(
[uid] => SimpleXMLElement Object
(
[0] => WOS:000238186400009
)
[journal] => SimpleXMLElement Object
(
[#attributes] => Array
(
[type] => source
)
)
[publication] => SimpleXMLElement Object
(
[#attributes] => Array
(
[type] => item
)
[0] => Abundance of hedgehogs (Erinaceus europaeus) in relation to the density and distribution of badgers (Meles meles)
)
[year] => 2006
[author1] => SimpleXMLElement Object
(
[0] => Young, RP
)
[address] => SimpleXMLElement Object
(
[0] => Cent Sci Lab, Sand Hutton, Yorks, England
)
[author2] => SimpleXMLElement Object
(
[0] => Davison, J
)
[author3] => SimpleXMLElement Object
(
[0] => Trewby, ID
)
[citations] => SimpleXMLElement Object
(
[#attributes] => Array
(
[local_count] => 15
[coll_id] => WOS
)
)
) ... etc ...
)
Can anyone help me with the method to get this data into my database, please? Do I need to change it into (yet) another format?
You have to iterate through your array to create a new array fulfilled with strings instead of SimpleXMLElement, such as :
<?php
// your array (already built)
$arraySimpleXml = array(
"example1" => new SimpleXMLElement("<test>value</test>"),
"example2" => new SimpleXMLElement("<test>value2</test>")
);
// output array, to store in database
$result = array();
foreach($arraySimpleXml as $key => $simpleXml) {
$result[$key] = $simpleXml->asXML();
}
// gets your result as a string => you can now insert it into mysql
$dbInsertion = serialize($result);
?>
So I worked out how to change the data into a standard array rather than an array of SimpleXMLElements so that I can successfully insert it into a MySQL database.
When iterating the SimpleXMLElement object to extract the data I needed I cast the type as String so that now my array has the format (as opposed to above):
Array
(
[0] => Array
(
[uid] => WOS:000238186400009
[journal] => JOURNAL OF ZOOLOGY
[publication] => Abundance of hedgehogs (Erinaceus europaeus) in relation to the density and distribution of badgers (Meles meles)
[year] => 2006
[author1] => Young, RP
[address] => Cent Sci Lab, Sand Hutton, Yorks, England
[author2] => Davison, J
[author3] => Trewby, ID
[citations] => 15
)
)
Thought I'd post this in case anyone has a similar problem in future. To do this, when iterating the data instead of:
$uid = $record->UID;
I did:
$uid = (string)$record->UID;
For each of the data fields I required. This ensures the data is stored as a String and so removes the SimpleXMLElement format.
I am retrieving a multidimensional php array (I think) from an API, now all of the values return perfectly and when I dump the array with print_r I get this:
Event Object
(
[title] => test
[link] => google.com
[updated] => 2013-03-06T12:08:56.521-05:00
[id] => test
[name] => Copy of Copy of Copy of Mar 05, 2013 - TEST4
[description] =>
[registered] => 2
[createdDate] => 2013-03-06T12:08:56.521-05:00
[status] => COMPLETE
[eventType] => OTHER
[eventLocation] => EventLocation Object
(
[location] => test
[addr1] => test
[addr2] =>
[addr3] =>
[city] => madrid
[state] => andalucia
[country] =>
[postalCode] => 06103
)
[registrationUrl] => https://google.com
[startDate] => 2013-03-07T13:00:00-05:00
[endDate] => 2013-03-07T13:00:00-05:00
[publishDate] => 2013-03-06T12:11:15.958-05:00
[attendedCount] => 0
[cancelledCount] => 0
[eventFeeRequired] => FALSE
[currencyType] => USD
[paymentOptions] => Array
(
)
[registrationTypes] => Array
(
[0] => RegistrationType Object
(
[name] =>
[registrationLimit] =>
[registrationClosedManually] =>
[guestLimit] =>
[ticketing] =>
[eventFees] => Array
(
)
)
)
)
Now bumbling through wit my basic PHP i have found that i can list all of the first array items from [title] to [eventType] like this:
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
while (list($key, $value) = each($Event)) {
echo "$key => $value \r\n<br/>";
}
?>
my question: All I need to do it retrieve [title] and [startDate] I don't need the rest now I could just hide the rest using Js and css but i am sure i am just being an idiot and there is an easier way to traverse this array so it only spits out the two values i need.
How do i do this?
You do not have to traverse the whole object. Just access the properties you want:
$title = $Event->title;
$startDate = $Event->startDate;
// or
echo $Event->title;
echo $Event->startDate;
It's actually an object - not an (associative) array!
What's the difference?
An object is an instance of a class. A class has methods and attributes (member variables).
Unlike C++ or some other OOP languages, you can define attributes dynamically without declaring them in the class declaration.
An array is simply a container for keys and their values.
It seems that it's not an array but an object so something like this:
echo $Event->title;
echo $Event->startDate;
Is it ...
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
echo $Event->$title . "<br/>";
echo $Event->$startDate . "<br/>";
?>
? Or am I too simple?
I want to display the Itinerary details from developer.ean.com API. By passing the customer's Itinerary ID and Email ID I got the details of reservation.
The result is comming in json format so I decoded it and creating array by using :
$array=json_decode($result);
The problem is whatever the result comming from API contain problem like :
For some records it providing array like this:
[Itinerary] => stdClass Object
(
[HotelConfirmation] => Array
(
[0] => stdClass Object
(
[supplierId] => 13
[chainCode] => EP
[arrivalDate] => 07/24/2012
[departureDate] => 07/26/2012
)
[Hotel] => Array
(
[0] => stdClass Object
(
[hotelId] => 394808
[statusCode] => A
[name] => Barkston Youth Hostel
)
)
)
)
In this case the HotelConfirmation and Hotel is Array which contain [0] as object
and for some records it providing array like this:
[Itinerary] => stdClass Object
(
[HotelConfirmation] => stdClass Object
(
[supplierId] => 13
[chainCode] => EP
[arrivalDate] => 07/24/2012
[departureDate] => 07/26/2012
)
[Hotel] => stdClass Object
(
[hotelId] => 394808
[statusCode] => A
[name] => Barkston Youth Hostel
)
)
and In this case the HotelConfirmation and Hotel is itself an object
I providing only few data here actually its big array and I want to provide list of it. But the array containing ambiguity like this. How can I handle this issue. Is there any solution.
Thanks in advance.
Pass true as the second argument to json_decode. This will create an array instead of stdClass
$array=json_decode($result, true);
you can normalize the input like so:
// get objects as arrays
$array = json_decode($result, true);
// remove the sub-level [0], when necessary
foreach ($array as $key => $value) {
if (is_array($value[0])) {
$array[$key] = $value[0];
}
}
Then the result always looks the same:
[Itinerary] => Array
(
[HotelConfirmation] => Array
(
[supplierId] => 13
[chainCode] => EP
[arrivalDate] => 07/24/2012
[departureDate] => 07/26/2012
)
[Hotel] => Array
(
[hotelId] => 394808
[statusCode] => A
[name] => Barkston Youth Hostel
)
)
First do this:
$array = json_decode($result, true);
Which will convert objects into associative arrays
And do adjustment like this:
if (isset($array['HotelItineraryResponse']['Itinerary']['HotelConfirmation'][0])) {
$array['HotelItineraryResponse']['Itinerary']['HotelConfirmation'] = $array['HotelItineraryResponse']['Itinerary']['HotelConfirmation'][0];
}
It will definitly work.
You can use is_array() to check for it:
if (is_array($hotel)) {
$hotel = $hotel[0];
}
just change to this:
$array=json_decode($result,TRUE);
and handle arrays always?
Looks like you may have to account for both possibilities in your model... Checking to see if the hotel node contains and array or an obj and operating accordingly.
you can type case the object inside of an array.
$array = json_decode($result);
$array = (array)$array
or alternatively you can pass true as the second argument in your json_decode();
according to php documentation
When TRUE, returned objects will be converted into associative arrays.
$array = json_decode($result, true);
Check for object or array:
if( is_object($Itinerary -> HotelConfirmation)) {
// do one thing or nothing
} elseif( is_array($Itinerary -> HotelConfirmation)) {
$Itinerary -> HotelConfirmation = array_shift( $Itinerary -> HotelConfirmation );
}
I've seen similar questions on here but I can't seem to apply the solutions to my problem. I have a variable called $results which I got from an API. I'll change the proper nouns so as to protect my work's customers:
stdClass Object
(
[out] => stdClass Object
(
[count] => 2
[transactions] => stdClass Object
(
[RealTimeCommissionDataV2] => Array
(
[0] => stdClass Object
(
[adId] => 12345678
[advertiserId] => 123456789
[advertiserName] => Chuck E. Cheese, inc.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:44:25-08:00
[orderId] => X-XXXXXXXXXX
[saleAmount] => 0
[sid] => 123456789
[websiteId] => 2211944
)
[1] => stdClass Object
(
[adId] => 987654321
[advertiserId] => 12345
[advertiserName] => Chorizon Wireless.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:58:40-08:00
[orderId] => X-CXXXXXX
[saleAmount] => 0
[sid] => 61-122112
[websiteId] => 1111922
)
)
)
)
)
I shortened it to two entries here but the number of entries will vary, it's the result of a check for transactions in the past hour, there may sometimes be only one and sometimes as many as a dozen.
I want to assign these entries to variables like websiteId1 websiteId2 etc. I know I need to do a foreach loop but can't seem to figure it out. How can I write it so that I get the "[details]" as well?
foreach ($results->out->transactions->RealTimeCommissionDataV2 AS $commissionData) {
// you can access the commissionData objects now, i.e.:
$commissionData->adId;
$commissionData->details;
}
<?
foreach ($result->out->transactions->RealTimeCommissionDataV2 as $item)
{
// do somthing with each item.
print_r($item);
// or the details array
$num_details = sizeof($item->details)
}
I think this is what you want.
EDIT
Updated based on some notes in the documentation. Specifically, these two
a numerically indexed array will not
produce results unless you use
EXTR_PREFIX_ALL or
EXTR_PREFIX_INVALID.
Prefixes are automatically separated
from the array key by an underscore
character.
echo extract( $results->out->transactions->RealTimeCommissionDataV2, EXTR_PREFIX_ALL, 'websiteId' );
// test the extract
print_r( $websiteId_0 );