[英]PHP Array to JavaScript Length
I wrote this code: 我写了这段代码:
$userAddresses = $database->getUsers("SELECT * FROM Users");
$address = array();
foreach($userAddresses as $user){
array_push($address, array("address"=> $user['address'],
"zipcode" => $user['zipcode']));
}
$locations = array(
"locations" => $address
);
$jsonLocations = json_encode($locations);
This code returns this json object: 此代码返回此json对象:
{"locations":[
{"address":"Sneekermeer 25","zipcode":"2993 RL"},
{"address":"Boeier 13","zipcode":"2992 AK"}]}
I want to get the length of this array inside JavaScript. 我想在JavaScript中获取此数组的长度。 So I did this: 所以我这样做:
var address = '<?php echo $jsonLocations ?>';
After that I called console.log(address.length);
之后,我调用了console.log(address.length);
to check the length but some how it counts all the chars (108 I think) in the address variable and returns that as length. 来检查长度,但是要检查它如何计算地址变量中的所有字符(我认为是108)并将其作为长度返回。 address.locations.length
also doesn't work. address.locations.length
也不起作用。
Could someone help me out? 有人可以帮我吗?
You can use JSON.parse() 您可以使用JSON.parse()
var address = JSON.parse('<?php echo $jsonLocations ?>');
console.log(address.length); // will give you length;
Thats because the string needs to be decoded to an object. 那是因为字符串需要解码为一个对象。 You can do this one of two ways. 您可以通过以下两种方法之一来执行此操作。
Non recommended: 不推荐:
var address = <?= $jsonLocations ?>;
Or more correctly and safer: 或更正确,更安全:
var address = JSON.parse('<?= addslashes(json_encode($jsonLocations)) ?>');
Do not forget the call to addslashes
to prevent any single quotes in your array from breaking the javascript string. 不要忘了对addslashes
的调用,以防止数组中的任何单引号破坏JavaScript字符串。
You can either remove the quotes around var address = '<?php echo $jsonLocations ?>';
您可以删除var address = '<?php echo $jsonLocations ?>';
周围的引号var address = '<?php echo $jsonLocations ?>';
(ie var address = <?php echo $jsonLocations ?>;
) or use JSON.parse
to parse it as a string to an object. (即var address = <?php echo $jsonLocations ?>;
)或使用JSON.parse
将其解析为对象的字符串。
I have tried the below and its working 我已经尝试了以下及其工作
var address = '{"locations":[{"address":"Sneekermeer 25","zipcode":"2993 RL"},{"address":"Boeier 13","zipcode":"2992 AK"}]}';
address = JSON.parse(address);
console.log(address.locations.length);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.