array_push key =>值,怎么办呢?

时间:2010-08-14 01:11:59

标签: php arrays array-push

我想在数组中按键和值,但我不能

$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");  
}

请帮助我..

谢谢^ _ ^

2 个答案:

答案 0 :(得分:3)

以下是我要做的事情:

$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=)。

答案 1 :(得分:2)

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

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

前者会使$arr包含$id=>$title。如果存在倍数,后者将使$arr包含$id=>array($title1,$title2,$title3)等。