【发布时间】:2018-05-10 03:23:29
【问题描述】:
我正在构建一个函数以在 php 中返回一个数组数组,如下所示:
function get_posts(){
$ids = $post_userids = $names=$langs=$countrys=$post_images=$post_dates= $post_date_updateds = array();
if ($countm = $mysqli->prepare("SELECT SQL_CALC_FOUND_ROWS id,post_userid,name,lang,country,post_image,post_date,post_date_updated FROM posts ORDER BY `post_date` DESC ;")) {
$countm->execute();
$countm->store_result();
$countm->bind_result($id,$post_userid,$name,$lang,$country,$post_image,$post_date,$post_date_updated); // get variables from result.
$nr = "SELECT FOUND_ROWS() ";
$r = $mysqli->prepare($nr);
$r->execute();
$r->bind_result($no_posts);
$r->fetch();
$r->close();
while ($l[] = $countm->fetch())
{
$ids[] = $id ;
$post_userids[] = $post_userid ;
$names[] = $name ;
$langs[] = $lang ;
$countrys[] = $country ;
$post_images[] = $post_image ;
$post_dates[] = $post_date ;
$post_date_updateds[] = $post_date_updated ;
} ;
$countm->close();
}else {printf("Prepared Statement Error: %s\n", $mysqli->error);}
return array('ids' => $ids,'post_userids' => $post_userids,'names' => $names,'langs' => $langs,'countrys' => $countrys,'post_images' => $post_images,'post_dates' => $post_dates,'post_date_updateds' => $post_date_updateds, 'no_posts' => $no_posts);
}
假设我的表中有两个条目,一个 ID 为 6,另一个 ID 为 7 当我尝试输出时
$get_posts = get_posts();
echo $get_posts['ids'][0] // it output 6
但是当我设置时
echo $get_posts['ids'][1] // to get id 7 it output error
这也行不通。
echo $get_posts['no_posts'] // it output error
我不知道是我做错了什么还是我错过了什么,或者是否有更好的方法来实现这一点。
编辑:
var_dump($get_posts)
给了
array(2) { ["ids"]=> array(1) { [0]=> int(6) } ["no_posts"]=> int(2) }
【问题讨论】:
-
请
var_dump($count_posts)并将输出添加到您的问题中。此外,您的代码似乎很难理解您要做什么。 -
在所示代码的任何地方都没有定义
count_posts函数。这一切看起来像是一个糟糕的科学实验出了问题 -
@charlietfl ,抱歉,已编辑
-
@Scuzzy 使用 var 转储编辑
-
为什么不只使用
$post[$row['id']] = $row并使用fetch_assoc?