note 45141 added to function.array-keys
| From: | glennh at webadept dot net | Date: | Fri, 27 Aug 2004 10:14:57 +0000 |
| Subject: | note 45141 added to function.array-keys | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-75412@lists.php.net to get a copy of this message | ||
One way i've used this function is binding arrays to objects from queries. such as :
<?
function User($uid)
{
$uq = "select * from customers where uid = '$uid'";
$ur = db_exec($uq);
$ua = db_fetch_assoc($ur);
$mykeys = array_keys($ua);
$len = count($mykeys);
for($i=0;$i < $len;$i++)
{
$this->$mykeys[$i] = $ua[$mykeys[$i]];
}
} // end function
?>
of course, it could be better to do this from the other angle as well.
<?
function bindHashToObject( $hash, &$obj, $prefix=NULL, $checkSlashes=true, $bindAll=false ) {
is_array( $hash ) or die( "bindHashToObject : hash expected" );
is_object( $obj ) or die( "bindHashToObject : object expected" );
if ($bindAll) {
foreach ($hash as $k => $v) {
$obj->$k = ($checkSlashes && get_magic_quotes_gpc()) ? stripslashes( $hash[$k] ) :
$hash[$k];
}
} else if ($prefix) {
foreach (get_object_vars($obj) as $k => $v) {
if (isset($hash[$prefix . $k ])) {
$obj->$k = ($checkSlashes && get_magic_quotes_gpc()) ? stripslashes( $hash[$k] ) :
$hash[$k];
}
}
} else {
foreach (get_object_vars($obj) as $k => $v)
{
if (isset($hash[$k]))
{
$obj->$k = ($checkSlashes && get_magic_quotes_gpc()) ? stripslashes( $hash[$k] ) :
$hash[$k];
}// end if
}// end foreach
} // end if else
//echo "obj="; print_r($obj); exit;
} // end function
?>
I'm not really sure which is the better method, but using the array_keys function has always
worked rather well for me, your milage may varry.
----
Manual Page -- http://www.php.net/manual/en/function.array-keys.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+45141
Delete -- http://master.php.net/manage/user-notes.php?action=delete+45141&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+45141&report=yes
Search -- http://master.php.net/manage/user-notes.php