【问题标题】:Returning array from PHP function only gives first element从 PHP 函数返回数组只给出第一个元素
【发布时间】:2017-11-09 09:12:20
【问题描述】:

我正在尝试使用数据库中的部分动态填充我网站的管理页面。

问题是我想将所有部分都添加到数据库中,为了更容易,我使用了一个函数。

这段代码打印出第一个数组元素。

functions.php

<?php
function fetchAdminSections ($user_id){
    global $pdo;

    $get_sections = $pdo->prepare("SELECT `id`, `section_name`, `section_description` FROM `administration_sections` WHERE `admin_added_this` = :admin");
    $get_sections->execute([
        ':admin' => $user_id
    ]);

    while ($row = $get_sections->fetch(PDO::FETCH_ASSOC)){
        $sections = [];

        $id = $row['id'];
        $name = $row['section_name'];
        $description = $row['section_description'];
        $sections[$id]['section_name'] = $name;
        $sections[$id]['section_description'] = $description;
        return $sections;
    }
}
?>

index.php

 <?php
    include 'functions.php';

    $elements = fetchAdminSections($user_id);
    print_r($elements);
 ?>

我得到的是:

Array ( [1] => Array ( [section_name] => test1 [section_description] => test ) )

简单地在while 中返回$row 给了我类似的东西:

Array ( [id] => 1 [section_name] => test1 [section_description] => test )

我想获取所有部分,并循环浏览它们!

【问题讨论】:

  • 循环后移动return $sections;
  • 每次循环时,您都会再次启动变量$sections,这意味着它会不断被覆盖。将此行 $sections = []; 移出循环。

标签: php arrays function


【解决方案1】:

您需要在循环外定义数组并在循环完成后返回...

<?php
function fetchAdminSections ($user_id){
    global $pdo;

    $get_sections = $pdo->prepare("SELECT `id`, `section_name`, `section_description` FROM `administration_sections` WHERE `admin_added_this` = :admin");
    $get_sections->execute([
        ':admin' => $user_id
    ]);

    $sections = [];
    while ($row = $get_sections->fetch(PDO::FETCH_ASSOC)){

        $id = $row['id'];
        $name = $row['section_name'];
        $description = $row['section_description'];
        $sections[$id]['section_name'] = $name;
        $sections[$id]['section_description'] = $description;
    }

    return $sections;
}
?>

【讨论】:

    【解决方案2】:

    您需要将 return 语句放在 while 循环之外。

    按照现在的方式,它在第一次运行时从 while 循环中返回。一个函数不能多次返回一个值。像这样编辑它:

    $sections = [];
    while ($row = $get_sections->fetch(PDO::FETCH_ASSOC)){
        $id = $row['id'];
        $name = $row['section_name'];
        $description = $row['section_description'];
        $sections[$id]['section_name'] = $name;
        $sections[$id]['section_description'] = $description;
    
    }
    return $sections;
    

    【讨论】:

      猜你喜欢
      • 2011-07-12
      • 2011-11-05
      • 2021-09-14
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      相关资源
      最近更新 更多