将函数结果返回到数组中


Returning function result into array

我将一个数组传递给一个函数,并期望该函数在其中存储值

功能-

    function GetDetailsById ($iStudentId, $aDetailsId)
    {
        /* SQL */
        while ($row = mysql_fetch_array($result))
        {
           array_push($aDetailsId, $row[0]);
        }
    }

用法-

    $aDetailsId = array();
    $oDetailsTable->GetDetailsById("1", $aDetailsId)

当我尝试做时

print_r($aDetailsId)

数组中没有显示任何内容。我这样做对吗?

您的数组需要通过引用传递给函数;这意味着函数应该这样定义:

function GetDetailsById ($iStudentId, & $aDetailsId)
{
  // ...
}

有关更多信息,请参阅通过引用传递参数


或者,您可以让函数返回其结果——这可能是更好的主意(查看调用该函数的代码,您会立即知道它的作用)

function GetDetailsById ($iStudentId)
{
    $result = array();
    // TODO here, fill $result with your data
    return $result;
}

并调用函数:

$aDetailsId = $oDetailsTable->GetDetailsById("1");

这是因为默认情况下,参数是通过值传递的,这意味着只有变量的值被传递到函数中,而不是变量本身。无论对函数内部的值做什么,都不会影响函数外部的原始值。

两种选择:

  1. return是函数的修改值
  2. 通过引用传递参数:

    function GetDetailsById ($iStudentId, &$aDetailsId) ...
    

第一次计数/检查您的resutl是否包含任何结果集。并尝试使用"&"在阵列的参数中

function GetDetailsById ($iStudentId, &$aDetailsId)

请将函数声明更改为,

function GetDetailsById ($iStudentId, &$aDetailsId)

array_push调用中还有一个错误。更改为,

array_push($aDetailsId, $row[0]);