force nested array [closed]
I have the following code which returns a simple array if one result is found and a nested array if more.
$query = @mysq开发者_如何学编程l_query( $q );
if ( $query ) {
$this->num_rows = mysql_num_rows( $query );
for ( $i = 0; $i < $this->num_rows; $i++ ) {
$r = mysql_fetch_array( $query );
$key = array_keys( $r );
for ( $x = 0; $x < count($key); $x++ ) {
// Sanitizes keys so only alphavalues are allowed
if( !is_int( $key[$x] ) ) {
if ( mysql_num_rows( $query ) > 1 ) {
$this->result[$i][$key[$x]] = $r[$key[$x]];
} else if ( mysql_num_rows( $query ) < 1 ) {
$this->result = null;
} else {
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
}
return true;
} else {
return false;
}
How to force it to always return a nested array and not a simple one?
I think your code can be reduced to:
$query = @mysql_query( $q );
if ( $query ) {
$this->num_rows = mysql_num_rows( $query );
if($this->num_rows) {
$this->result = array();
while(($row = mysql_fetch_assoc($query))) {
$this->result[] = $row;
}
}
else {
$this->result = null;
}
return true;
}
else {
return false;
}
Reference: mysql_fetch_assoc
Tip: Read and browse the documentation.
using your code (I think) this is what you need:
if ( mysql_num_rows( $query ) > 1 ) {
$this->result[$i][$key[$x]] = $r[$key[$x]];
} else if ( mysql_num_rows( $query ) < 1 ) {
$this->result = null;
} else {
// adding index 0 to $this->result[0] or you could use $i (maybe)
$this->result[0][$key[$x]] = $r[$key[$x]];
}
精彩评论