I am using one of the jquery ui autocomplete functions and have a requirement to create a php array populated in a foreach loop containing results from a PDO SELECT query.

The resultant array should look like this:

Array(
"result1"=>"result1",
"result2"=>"result2",   
"result3"=>"result3",
"result4"=>"result4"
"remaining results"=>"remaining results"
);

I tried this:

echo '$items = array(';
foreach($resulttags as $tag_rows)
{
$tags_display = $tag_rows['tag'];
echo '"' . $tags_display . '"=>"' . $tags_display . '",';
}
echo ");";

That echos out the array on the page but it does not work. I also tried this:

$items = array(); 
foreach($resulttags as $tag_rows)
{    
$results['"' . $tag_rows['tag'] . '"'] = '"' . $tag_rows['tag'] . '"'; 
}

But this results in square brackets around the array keys, and does not seem to want to work with the autocomplete. I am assuming the downvotes are b'c I did not show what I had tried already, I posted the question on my iPhone, and am now back to my laptop.

Im thinking this shouldnt be too hard but I have tried a number of approaches that have not worked. Any suggestions? These arrays Always give me fits, have not gotten my head around them yet.

share|improve this question
    
What have you tried? We'll help you with existing code. We won't give you something for nothing though. – Daedalus Sep 16 '12 at 1:25
1  
You're not building a PHP array... you're building a STRING that could be interpreted as an array if the moon and planets are properly aligned. – Marc B Sep 16 '12 at 1:57
    
Yeah, I had a feeling that my first try was just building a string. It is helpful to know that is not the right approach. I will continue tinkering with my other approach then. – Cbomb Sep 16 '12 at 2:00
    
php.net/array_push is what you want, and its equivalent shortcut $var[] = .... – Marc B Sep 16 '12 at 2:23
    
Thanks. That last downvote just seems like piling on. – Cbomb Sep 16 '12 at 3:50

Turns out I was just being stupid. I did this and it worked just fine:

$items = array();  
foreach($resulttags as $tag_rows)
{
$items[$tag_rows['tag']] = $tag_rows['tag'];
}

For some stupid reason I was trying to get the output from print_r to match the php code that I was trying to recreate from the autocomplete demo. Instead of getting the two outputs from print_r to match. Pretty dumb. Cost myself three downvotes too.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.