0

I am using jquery autocomplete and trying to define the values for the auto complete options.

I am trying to create a javascript variable from a php array. So far i have:

<?php
$usernames = get_records_sql("SELECT firstname,lastname FROM {$CFG->prefix}user ORDER BY lastname DESC");    
?>

<script language="javascript">
var names = ['<?php echo $usernames; ?>'];
</script>

I just need to convert the array to this format

var names= ["firstname lastname", "firstname lastname", "firstname lastname"];

Any help would be much appreciated.

3
  • What is the output of <?php echo $usernames; ?>? Commented Nov 17, 2011 at 12:34
  • Array ( [testing] => stdClass Object ( [lastname] => testing [firstname] => testing ) [test] => stdClass Object ( [lastname] => testing [firstname] => test ) [ab-temp] => stdClass Object ( [lastname] => test [firstname] => ab-temp ) ) Commented Nov 17, 2011 at 12:45
  • Can't see how this can be converted directly to JS array - looks like Peter answer has most chances to do what you're after. Commented Nov 17, 2011 at 12:47

3 Answers 3

2

Use the json_encode() function to encode a PHP array to a JavaScript array.

You can modify the below code to your specifications:

$arr = array();
// depending on the value get_records_sql() returns, you may have to modify
// this loop:
foreach($usernames as $row)
{
    $arr[] = $row['firstname'] . ' ' . $row['lastname'];
}
$output = json_encode($arr);
Sign up to request clarification or add additional context in comments.

1 Comment

he wants "firstname lastname"
1
var names = [<?php 
    $tmp = Array();
    foreach($usernames as $row) $tmp[] = '"'.$row->firstname.' '.$row->lastname.'"'; 
    echo join(',', $tmp);
?>];

3 Comments

hi peter, thanks for the answer. I cant get it working though. $usernames outputs as - Array ( [testing] => stdClass Object ( [lastname] => testing [firstname] => testing ) [test] => stdClass Object ( [lastname] => testing [firstname] => test ) [ab-temp] => stdClass Object ( [lastname] => test [firstname] => ab-temp ) )
Ok so your rows are objects (not arrays). So you may use $row->column_name instead $row['column_name']. I updated my answer.
:) thank you very much, it works like a dream. I should have known that.
0

This should work (untested)

foreach ($usernames as $key => $row) {
    $user[] = $row['firstname'].' '.$row['lastname'];
}

echo "<script language=\"javascript\">var names = ['" . implode(',',$user) . "'];</script>";

Cycle through rows, append each name to array $user, implode the array into a string and output.

Comments

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.