简体   繁体   中英

convert a php string array into a js array in js

I have an array from data that's retrieved from AJAX (which it comes from MVC-view-cakephp). I want to refill the array into combobox. Array looks like this:

Array (
    [266] => Andy Employee II
    [26] => Annette Oliveira
    [214] => Edwina Umeyor
    [39] => Eva Britton
    [193] => Leigh Otterson
    [68] => Louise Edelston
    [71] => Margaret Williams
    [97] => Simon Harris
)

You will use the json_encode function to turn a PHP array into a JavaScript object. More information on json_encode can be found in the PHP manual .

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

you would use the php json_encode function like

<script type="text/javascript">
var arr = <?php echo json_encode($myarray);?>;
</script>

I guess you'd have to write a custom parser to do this. You're unlikely to find one on the internet.

The preferable solution here is to have the cakephp script output this array as JSON. JSON can be easily produced by php using json_encode and of course javascript is very good at reading a JSON object.

Javascript doesn't have associative arrays. Instead, they use objects. In your PHP echo json_encode( $yourArray ); instead of whatever you are returning now (looks like a vardump?).

In your AJAX call set up JSON to be the expected content return type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM