php中数组的返回数组
我正在构建一个函数来返回php中的数组,如下所示:php中数组的返回数组,php,arrays,mysqli,Php,Arrays,Mysqli,我正在构建一个函数来返回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,nam
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) }
尝试以下简单方法:
function get_posts(){
$posts = array();
if ($result = $mysqli->query("SELECT id, post_userid, name, lang, country, post_image, post_date, post_date_updated FROM posts ORDER BY `post_date` DESC ;")) {
while ($row = $result->fetch_assoc())
{
$posts[$row['id']] = $row ;
}
} else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
return $posts;
}
请
var\u dump($count\u posts)
并将输出添加到您的问题中。此外,您的代码似乎很难理解您要做什么。在显示的代码中,没有定义任何count\u posts
函数。这一切看起来像是一个糟糕的科学实验wrong@charlietfl对不起,edited@Scuzzy使用var dumps编辑为什么不使用$post[$row['id']]=$row
并使用fetch\u assoc
?其他值、名称、语言呢?请尝试并转储$posts
所有都在内部,因为id
6,$post[6]
将是一个关联数组,名称是$post[6]['name']
您的意思是var\u dump($get\u posts),我不能转储帖子,它的内部函数我不明白你可以转储内部函数,顺便说一下,转储函数的结果足够了,我必须给出id是6吗?我不想给我身份证,因为每次都不一样。我只想把所有的东西都拿出来,我也试过把垃圾倒在里面,但没用