array_push key=>value ,怎么办?

发布于 2024-09-14 07:03:22 字数 556 浏览 3 评论 0原文

我想将键和值推送到数组中,但我无法

$con = mysqli_connect('localhost','root','','wp') or die (mysqli_error('Error:'));

$query = mysqli_query($con,'set names utf8')or die (mysql_error());
$qy = mysqli_query($con,"SELECT ID,post_title FROM wp_posts WHERE post_type='page' AND post_status='publish'")or die (mysql_error());
$arr = array();
while ($row = mysqli_fetch_array($qy)){
$id = "?page_id=".$row['ID'];
$title = $row['post_title'];
$arr[] = $id . "=>" . $title;
array_push($arr, "$id" => "$title");  
}

帮助我..

谢谢^_^

I want to push key and value in array , but I can't

$con = mysqli_connect('localhost','root','','wp') or die (mysqli_error('Error:'));

$query = mysqli_query($con,'set names utf8')or die (mysql_error());
$qy = mysqli_query($con,"SELECT ID,post_title FROM wp_posts WHERE post_type='page' AND post_status='publish'")or die (mysql_error());
$arr = array();
while ($row = mysqli_fetch_array($qy)){
$id = "?page_id=".$row['ID'];
$title = $row['post_title'];
$arr[] = $id . "=>" . $title;
array_push($arr, "$id" => "$title");  
}

plz help me ..

thanks ^_^

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

强辩 2024-09-21 07:03:22

这就是我会做的:

$arr = array();
while ($row = mysqli_fetch_assoc($qy)){
    $id = $row['ID'];
    $arr[$id] = $row['post_title'];
}

然后当您需要打印它们时:

foreach ($arr as $id => $title) {
    echo "?page_id={$id}'>{$title}</a>";
    // or whatever, depends on how you want to print it
}

不要在数组中存储不必要的信息(即:?page_id=)。

Here's what I would do instead:

$arr = array();
while ($row = mysqli_fetch_assoc($qy)){
    $id = $row['ID'];
    $arr[$id] = $row['post_title'];
}

And then when you need to print them:

foreach ($arr as $id => $title) {
    echo "?page_id={$id}'>{$title}</a>";
    // or whatever, depends on how you want to print it
}

Don't store unnecessary information (ie: ?page_id=) in arrays.

红ご颜醉 2024-09-21 07:03:22

您想要执行$arr[$id] = $title吗?或者你想要这个:

if (!isSet($arr[$id])) {
    $arr[$id] = array();
}
$arr[$id][] = $title;

前者将使 $arr 包含 $id=>$title。如果有多个,后者将使 $arr 包含 $id=>array($title1,$title2,$title3) 等。

Do you want to do $arr[$id] = $title? Or do you want this:

if (!isSet($arr[$id])) {
    $arr[$id] = array();
}
$arr[$id][] = $title;

The former will make it so that $arr contains $id=>$title. The latter will make it so that $arr contains $id=>array($title1,$title2,$title3) etc if there are multiples.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文