Codded
Codded

Reputation: 1256

php array in javascript variable for jquery autocomplete

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.

Upvotes: 0

Views: 1874

Answers (3)

Peter
Peter

Reputation: 16943

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

Upvotes: 2

user142162
user142162

Reputation:

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);

Upvotes: 2

David Barker
David Barker

Reputation: 14620

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.

Upvotes: 0

Related Questions