0

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

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

thank you very much , the result is fail .. this is the result $My_links = array('2' => 'Array' ,'4' => 'Array' ,'6' => 'Array' ,'9' => 'Array' ,'11' => 'Array' ,'13' => 'Array' ,'45' => 'Array' );
@AboSami: Yes, if you use the second bit of code, that should be the result. If you use just $arr[$id] = $title, it will not, but your IDs had better be unique!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.