Afficher un message
Vieux 16/03/2008, 03h16   #3
Jeremy Mcentire
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: [PHP] Objects as array key names??

On Mar 15, 2008, at 7:16 PM, Ray Hauge wrote:
> Jim Lucas wrote:
>> It has been brought to my attention that with Perl and Ruby, you
>> can use Objects as the value of the key within an array. The
>> examples that were shown to me make me think that this would be an
>> awesome ability to have within PHP.
>> $res = query('Select c_id, c_first_name, c_last_name FROM
>> customers');
>> $customers = array();
>> while ( $row = fetch_assoc($res) ) {
>> $customers[$row]['contact_locations'] = array();
>> $SQL = "SELECT *
>> FROM contact_locations
>> WHERE c_id={$row['c_id']}";
>> $loc_res = query($SQL);
>> while ( $loc_row = fetch_assoc($loc_res) ) {
>> $customers[$row]['contact_locations'][] = $loc_row;
>> }
>> }
>> Now, contained within one array "$customers" I have all the
>> information that would be needed for displaying any type of
>> information related to a customer or a customers location.
>>


You may have meant the while loop to iterate over $row =
fetch_object($res) ...

> // START CODE //
> $cid = null;
> $customers = array();
>
> while ( $row = fetch_assoc($res) ) {
>
> $cid = $row['cid'];
> $customers[$cid] = $row;
> $customers[$cid]['contact_locations'] = array();
>
> $SQL = "SELECT *
> FROM contact_locations
> WHERE c_id={$cid}";
>
> $loc_res = query($SQL);
>
> while ( $loc_row = fetch_assoc($loc_res) ) {
> $customers[$cid]['contact_locations'][] = $loc_row;
> }
>
> }
> // END CODE //




You could also create a data object associated with customer that
makes use of overloading functions -- or whatever you kids are calling
them these days to allow:

$customer = new Customer(78); // Load customer with ID 78.
$customer->loadLocations(); // Loads related locations.
$customer->location[n]; // Returns nth location.
$customer->location('home'); // Returns the location dubbed "home."
// You can have location loadLocations() if they're not already set.

The data object would have to make use of __get, __set, and __call.

Hereby, the locations aren't indexed by the object, but are elements
in a member array.
  Réponse avec citation
 
Page generated in 0,05264 seconds with 9 queries