-4

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.

5
  • What have you tried? We'll help you with existing code. We won't give you something for nothing though. Commented Sep 16, 2012 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. Commented Sep 16, 2012 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. Commented Sep 16, 2012 at 2:00
  • php.net/array_push is what you want, and its equivalent shortcut $var[] = .... Commented Sep 16, 2012 at 2:23
  • Thanks. That last downvote just seems like piling on. Commented Sep 16, 2012 at 3:50

1 Answer 1

0

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.

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.