Sander Bakker
Sander Bakker

Reputation: 35

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:

{"locations":[
             {"address":"Sneekermeer 25","zipcode":"2993 RL"},
             {"address":"Boeier 13","zipcode":"2992 AK"}]}

I want to get the length of this array inside JavaScript. So I did this:

var address = '<?php echo $jsonLocations ?>';

After that I called 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. address.locations.length also doesn't work.

Could someone help me out?

Upvotes: 0

Views: 174

Answers (4)

Mad Angle
Mad Angle

Reputation: 2330

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

Upvotes: -1

Geoffrey
Geoffrey

Reputation: 11353

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.

Upvotes: 1

ZombieTfk
ZombieTfk

Reputation: 712

You can either remove the quotes around var address = '<?php echo $jsonLocations ?>'; (i.e var address = <?php echo $jsonLocations ?>;) or use JSON.parse to parse it as a string to an object.

Upvotes: 0

Dinesh undefined
Dinesh undefined

Reputation: 5546

You can use JSON.parse()

var address = JSON.parse('<?php echo $jsonLocations ?>');

console.log(address.length); //  will give you length;

Upvotes: 2

Related Questions