force nested array [closed]

自闭症网瘾萝莉.ら 提交于 2019-12-24 19:23:08

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/6454420/force-nested-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!