【问题标题】:foreach loop only outputs the last element from arrayforeach 循环仅输出数组中的最后一个元素
【发布时间】:2019-10-22 07:00:31
【问题描述】:

我做了一个选择语句,它有多个输出。

但是当我尝试返回时,它只会返回最后一个。 这是我的代码...

$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 个结果,但我的 return 只返回 var dump 的最后一个结果。

我在这里做错了什么?

【问题讨论】:

    标签: php arrays pdo foreach


    【解决方案1】:

    您正在重写代码中的值。您需要将每个结果推送到数组。请参阅下面的代码以供参考。

    $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;
    

    【讨论】:

      【解决方案2】:

      如果您正确构建查询,则不需要foreach

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

      然后只需获取所有行并返回它们:

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

      【讨论】:

      • 嘿,我确实尝试过类似SELECT profile`.rolle, ( `profile`.`name` , " " , `profile`.nachname ) AS full_name, 但它返回的操作数应该包含 1 列
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      相关资源
      最近更新 更多