从PHP函数返回数组只给出第一个元素
我试图用数据库中的部分动态填充我站点的管理页面 问题是我想把所有的部分都添加到数据库中,为了方便起见,我使用了一个函数 这段代码打印出第一个数组元素从PHP函数返回数组只给出第一个元素,php,arrays,function,Php,Arrays,Function,我试图用数据库中的部分动态填充我站点的管理页面 问题是我想把所有的部分都添加到数据库中,为了方便起见,我使用了一个函数 这段代码打印出第一个数组元素 functions.php <?php function fetchAdminSections ($user_id){ global $pdo; $get_sections = $pdo->prepare("SELECT `id`, `section_name`, `section_description` FROM
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;
}
}
?>
<?php
include 'functions.php';
$elements = fetchAdminSections($user_id);
print_r($elements);
?>
我得到的是:
Array ( [1] => Array ( [section_name] => test1 [section_description] => test ) )
只需在中返回$row
,而会给我一个类似的结果:
Array ( [id] => 1 [section_name] => test1 [section_description] => test )
我想得到所有的部分,并循环通过它们 您需要在循环外部定义数组,并在循环完成后返回
<?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;
}
?>
您需要将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;
移动返回$sections代码>循环后每次循环都会再次启动变量$sections
,这意味着它会不断被覆盖。移动此行$sections=[]代码>循环外部。