簡體   English   中英

foreach循環僅輸出數組中的最后一個元素

[英]foreach loop only outputs the last element from array

我做了一個選擇陳述,其中有多個輸出。

但是當我嘗試返回時,它只會重現最后一個。 這是我的代碼...

$stmt->execute();
$row = $stmt->fetchAll();

$result = [];

foreach ($row as $fullName => $type) {
    $result['fullName'] = $type['name'] . ' ' .$type['lastname'];
    $result['class_type'] = $type['typ'];

    var_dump($result['fullName']);
}

return $result;

我的var-dump返回4個結果,但是我的返回僅返回var dump中的最后一個結果。

我在這里做錯了什么?

如果您正確構建查詢,則無需foreach

SELECT CONCAT(name, " ", lastname) AS fullName, typ AS class_type FROM table_name

然后只需獲取所有行並返回它們:

$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);

您正在代碼中重寫值。 您需要將每個結果推送到數組。 請參閱下面的代碼以供參考。

$stmt->execute();
$row = $stmt->fetchAll();

$result = [ ];

foreach ($row as $fullName => $type) {
    $result[] = [
    'fullName' => $type['name'] . ' ' .$type['lastname'],
    'class_type' => $type['typ'] ];

   // var_dump($result['fullName']);
}

return $result;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM