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

Jim Lucas wrote:
> This question should probably be directed at the PHP Internals list, but
> I thought I would start by asking here first if anybody would even use
> this feature.
>
> 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.
>
> Here is an example of how I would use such a feature.
>
> I have a table of "customers".
> I have a table customers "contact_locations".
> This table has a reference ID back to the "customers" table.
>
> Now, in my array of information that I build I have this.
>
> $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.
>
> By doing having this feature, I could build the ability to do xPath
> searches within the base array. That would be nice.
>
> Anyways, what do you all think? Worth it or not?
>
> Jim Lucas
>


Maybe I don't get the new concept, but what would be wrong with:

// 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 //

Now you can easily reference all of your customers by ID and get any of
the data you want. I would actually just load the record I want from
the database and not chew up all that memory, but this is just an
example anyway.

I guess it could allow you to somewhat consolidate a two-dimensional
array down to a single dimension. In order to use the data, you'd have
to use array_keys() or something similar to use it though.

It's an interesting idea, but I don't know how practical it would be.

--
Ray Hauge
www.primateapplications.com
  Réponse avec citation
 
Page generated in 0,05548 seconds with 9 queries