从PHP函数返回数组只给出第一个元素

时间:2017-11-09 09:12:20

标签: php arrays function

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

问题是我希望在数据库中添加所有部分,并且对我来说更容易,我使用了一个函数。

此代码将我打印出第一个数组元素。

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 ) )

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

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

我想获得所有部分,并循环使用它们!

2 个答案:

答案 0 :(得分:2)

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

<?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;
}
?>

答案 1 :(得分:1)

您需要将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;