强制嵌套数组 [英] force nested array
本文介绍了强制嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,如果找到一个结果,则返回一个简单数组,如果发现更多,则返回一个嵌套数组。
I have the following code which returns a simple array if one result is found and a nested array if more.
$query = @mysql_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;
}
提示:阅读并浏览文档。
Tip: Read and browse the documentation.
这篇关于强制嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文