Re: Objects as array key names??
| From: | Jeremy Mcentire | Date: | Sun, 16 Mar 2008 01:16:24 +0000 |
| Subject: | Re: Objects as array key names?? | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-271652@lists.php.net to get a copy of this message | ||
On Mar 15, 2008, at 7:16 PM, Ray Hauge wrote:
Jim Lucas wrote:You may have meant the while loop to iterate over $row = fetch_object($res) ...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.
// START CODE // $cid = null; $customers = array(); while ( $row = fetch_assoc($res) ) { $cid = $row['cid']; $customers[$cid] = $row; $customers[$cid]['contact_locations'] = array(); $SQL = "SELECT *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.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 //