从 yii2 中的函数获取多个值

Get multiple values from a function in yii2

我的 Model 中有一个函数,它传递了一个值,其中有一个查询给出了两个结果。

 public static function updImgtbl($id)
{
    $total_images = 0;
    $images_uploaded = 0;

    $sqlquery = "SELECT  SUM(CASE WHEN ims.`installation_id` = $id THEN 1 ELSE 0 END) AS total_images, 
    SUM(CASE WHEN ims.`image_upload_flag` = 1 AND ims.`installation_id` = $id THEN 1 ELSE 0 END) AS images_uploaded
    FROM    `installation_images_site` ims
    INNER JOIN `installations` ins ON ins.`id` = ims.`installation_id`
    WHERE   (ims.`image_upload_flag` = 1 AND ims.`installation_id` = $id)
    OR (ims.`installation_id` = $id) 
    GROUP BY ims.`installation_id`";

    $pt = Yii::$app->db->createCommand($sqlquery)->queryAll();

    foreach ($pt as $val)
    {
        $total_images= $val['total_images'];
        $images_uploaded = $val['images_uploaded'];
    }
    return ["total_images" => $total_images, "images_uploaded"=>$images_uploaded];
}

此函数是从 API

调用的
 $response = Installations::updImgtbl($install_id);
        print_r($response);
        exit();

回复如下

Array
(
  [total_images] => 4
  [images_uploaded] => 1
)

但我想在 API 的变量中获取这些值。我怎样才能实现它?

您可以简单地:

list($total_images, $images_uploaded) = array_values($response);

然后,$total_images 变量中有 total_images 值,$images_uploaded 变量中有 images_uploaded 值。

我的意思是:

list($total_images, $images_uploaded) = Installations::updImgtbl($install_id);
echo $total_images; // 4
echo $images_uploaded; // 1

您可以在 official doc 中阅读有关 list 的更多信息。

另一种方法是使用 extract() 函数。例如:

$response = Installations::updImgtbl($install_id);
extract($response);   
echo $total_images; // 4
echo $images_uploaded; // 1