Traversing Object
Posted: Tue Apr 24, 2007 7:04 pm
Hello,
I am really quite new to PHP and have a question about efficient access and retrieval of object data. Because I don't know all the shortcut functions that can do this, I've got this awkward way of accessing object elements. First, here is an excerpt of object whose data I"m trying to access when calling print_r($profile):
I've altered real values for security reasons, but this is an example of Objects inside Objects and Arrays of Objects and this is my way of accessing elements:
This is clearly a time-consuming approach of accessing objects and objects inside objects. My question is:
Is there a more efficient way of doing this? Perhaps recursion or some PHP accessor methods that can access objects inside objects and retrieve values?
Please help,
Thank you,
Victor.
I am really quite new to PHP and have a question about efficient access and retrieval of object data. Because I don't know all the shortcut functions that can do this, I've got this awkward way of accessing object elements. First, here is an excerpt of object whose data I"m trying to access when calling print_r($profile):
Code: Select all
stdClass Object
(
[clientProfile] => stdClass Object
(
[passenger] => stdClass Object
(
[firstName] => Joe
[middleName] =>
[lastName] => User
[birthday] => 2007-03-02T00:00:00
[passengerType] => Adult
[gender] => Male
[passengerTitle] => Mr
[parentIndex] => -1
)
[agentId] => 0
[arrayOfAddresses] => stdClass Object
(
[Address] => stdClass Object
(
[streetNumber] => 735
[subAddressType] => None
[subAddressNumber] =>
[streetName] => Hello St
[streetDirection] => None
[cityName] => Moon
[stateCode] => BC
[countryCode] => CA
[postalCode] => 12345
)
)Code: Select all
$data = Array();
$personal_data = Array();
$address_data = Array();
$phone_data = Array();
$i = 0;
foreach($profile as $key => $value)
{
$data[$i] = $value;
$i++;
}
$i = 0;
foreach($data[0] as $key => $value)
{
$personal_data[$i] = $value;
$i++;
}
$i = 0;
//Acquire ADDRESS information about users
foreach($personal_data[2] as $key => $value)
{
$address_data[$i] = $value;
$i++;
}
//Display address information about users
foreach($address_data[0] as $key => $value)
{
echo "$key $value\n";
}Is there a more efficient way of doing this? Perhaps recursion or some PHP accessor methods that can access objects inside objects and retrieve values?
Please help,
Thank you,
Victor.