Search code examples
phparraysarray-push

array_push key=>value , how can do it?


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 ^_^


Solution

  • 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.