首页 > 解决方案 > PHP在函数中返回一个数组

问题描述

我是 PHP MySqli 的新手,这是我的第一个项目。我试图通过放入一个数组来从函数返回一个值。

function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
    global $connection;
    $sql = "SELECT ".$id."  FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";

    if ($result = mysqli_query($connection,$sql)) {
        $count = 0;
        while ($row = mysqli_fetch_array($result)) {
            $count = ++ $count; 
        }
        echo "<br>".$type.": " .  $count;
        $counter[$type] = $count;
        return $counter;      
    }

    $type = 'RIDDOR - Major Injury';
    riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
    var_dump($counter);

该函数工作到将打印结果的程度,该结果基本上是数组的各种计数。但是,我需要在其他地方的表中使用返回,但 var-dump 只返回 NULL。

标签: phparrayscountreturn

解决方案


As all the comment above - you are using $counter as if it global variable - if that is the case you can add global $counter at the begin of the function else if you want to use as return value you can add it to the function argument.

Option 1 - use global variable

function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
    global $connection;
    global $counter;
    $sql = "SELECT ".$id."  FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";

    if ($result = mysqli_query($connection,$sql)) {
        $count = mysqli_num_rows($result);
        echo "<br>".$type.": " .  $count;
        $counter[$type] = $count;     
    }
}

$type = 'RIDDOR - Major Injury';
riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
var_dump($counter);

Option 2 - use return value

function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
    global $connection;
    $sql = "SELECT ".$id."  FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";

    if ($result = mysqli_query($connection,$sql)) {
        $count = mysqli_num_rows($result);
        echo "<br>".$type.": " .  $count;
        return $count;     
    }
}

$type = 'RIDDOR - Major Injury';
$counter[$type] = riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
var_dump($counter);

I strongly recommend the second option to avoid using global...


推荐阅读