开发者

force nested array [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

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]]; 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜