php函数返回foreach循环后的最后一行


php function returns the last row after foreach loop

以下函数只返回数组的最后一行:

function myFunc () {
            $sql = mySql(); 
            $stid = oci_parse(getConnect(),$sql);
// runs the query above                   
oci_execute($stid);
if (oci_execute($stid)) {
            while ($row =oci_fetch_array($stid,OCI_ASSOC+OCI_RETURN_NULLS)) {
                   $out1 = "";
                   foreach($row as $column =>$entry)
                           $out1 .= $entry;
                   $output = $out1;         
                   //var_dump($output); - here I can see all array elements                                                               
                                                                            }   
 return($output);
}                       
else return "No Oracle connection";
}

var_dump()显示所有数组元素,但函数只显示数组的最后一行。是因为函数的返回吗?我必须返回一个数组才能获得所有数组元素吗?如何在一个字符串中获取所有数组元素?

在每个循环迭代中覆盖$output。您需要将这些值存储在一个数组中(或者根据您最终想要的内容附加它们):

$output = array();
while ($row = oci_fetch_array($stid,OCI_ASSOC+OCI_RETURN_NULLS)) {
    $out1 = "";
    foreach($row as $column =>$entry) {
        $out1 .= $entry;                                                          
    }   
    $output[] = $out1; 
}         
return($output);

这个函数有点复杂,我相信从查询开始可以大大简化。

我会使用这两种方法中的一种,这取决于您希望返回的数组的格式。

function myFunc () {
    $sql = mySql(); 
    $stid = oci_parse(getConnect(),$sql);             
    oci_execute($stid);
    $output = array();
    if (oci_execute($stid)) {
        for( $i = 0; $r = oci_fetch_array( $stid, OCI_ASSOC+OCI_RETURN_NULLS ) ){
            $output[$i] = $r;
        }
    }   
    return $output;
}            

//这将把整个结果数组放在一个数组中。如果结果包含多行,则会产生多数组结果。

function myFunc () {
    $sql = mySql(); 
    $stid = oci_parse(getConnect(),$sql);             
    oci_execute($stid);
    $output = array();
    if (oci_execute($stid)) {
        while( $row = oci_fetch_array( $stid, OCI_ASSOC+OCI_RETURN_NULLS ) ){
            foreach( $row AS $key => $val ){
                $output[] = $val;
            }
        }
    }   
    return $output;
} 

//这将把每个值作为数组对象放入$output数组

我完全同意约翰的观点。

然而,他比我快。

但这是我的:

function myFunc() {
    $sql    = mySql(); 
    $stid   = oci_parse(getConnect(), $sql);
    // runs the query above                   
    $result = oci_execute($stid);
    if ($result) {
       $arr = array();
       while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
            foreach($row as $column => $entry) {
                $arr[] = $entry;
            }                                                        
        } 
        $output = $arr; // you can simply go return($arr) but I've left it like this for debugging if you need
        return($output);
    } else {
        return "No Oracle connection: " . $result;
    }
}

我所做的是添加oci_execute()的$result,以便在连接中断时进行调试。我还将附加的字符串转换为数组。

希望能有所帮助。