简体   繁体   中英

Iterating through PHP array in javascript I get error in my each statement

I have a php array:

$array = array(‘1234’=>”Acme Company”,
    “4321”=>”CustomerX”,
    ”1056=>”CustomerY”,
    ”1058”=>”google”,
    ”1059”=>”Yahoo”,
    ”1060”=>”apple”);

I am attempting to create an autocomplete with this data. so step 1 is to iterate through in javascript.

 var clients = '<?php echo json_encode($array);?>';
  $.each(clients, function(i,el){
            alert(i+","+el);
    });

When i do this, I get the error:

Uncaught TypeError: Cannot use 'in' operator to search for '2847' in {“1234”:”Acme Company”,”4321”:”CustomerX,”1056”:”CustomerY”,”1058”:”google”,”1059”:”Yahoo”,”1060”:”Apple}

I can not figure out why. if i alert(clients) , it looks like a good array..

var client_parsed = JSON.parse(client);

然后使用client_parsed

Try it like this, you had error with passing php variable into your js var. Now it`s iterating through all of the array elements.

<?php
$array = ['1234'=>'Acme Company',
    '432'=>'CustomerX',
    '1056'=>'Customer',
    '1058'=>'google',
    '1059'=>'Yahoo',
    '106'=>'apple'];

    $array = json_encode($array);

    ?>

<script type="text/javascript">

    var clients = <?php echo $array; ?>;
    console.log(clients);
  $.each(clients, function(i,el){
            alert(i+","+el);
    });

    </script>

Use clients = $.parseJSON(clients); before each ( and remove " ' from the numbers.

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