Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  27] [ 6]  / answers: 1 / hits: 44472  / 13 Years ago, thu, february 16, 2012, 12:00:00

I have a multidimensional array like this



Array
(
[1] => Array
(
[product_id] => 1
[product_model] => HFJ5G1.5
[product_type] => plat
[product_return] => graviteits

)

[2] => Array
(
[product_id] => 2
[product_model] => HHJ5S2.5
[product_type] => holle plunjer
[product_return] => veer

)
); //Only 2 are shown here i have around 110 values


And i encoded this to json by



json_encode($array);


The resulted jsonString is something like this



{1:{product_id:1,product_model:HFJ5G1.5,product_type:plat,product_return:graviteits},2:{product_id:2,product_model:HHJ5S2.5,product_type:holle plunjer,product_return:veer}}


when i do alert(jsonString.length); the result is 4 But i want the result to be 2 am i doing something wrong .


More From » arrays

 Answers
9

an object literal has no .length



you can count properties using this method:



var count = 0;

for (i in jsonString) {
if (jsonString.hasOwnProperty(i)) {
count++;
}
}

alert(count); //count shall have length for you


OR



since your array didn't have numeric indices (starting from 0), it assumed you used an associative array, hence they dumped an object of items rather than an array of items.



to turn them to numeric indices, all you have to do is use array_values before encoding them to json:



json_encode(array_values($array));


then the json will be an array.. then you can use length



from this:



Array(
[1] => Array(
[product_id] => 1
[product_model] => HFJ5G1.5
[product_type] => plat
[product_return] => graviteits
)
[2] => Array(
[product_id] => 2
[product_model] => HHJ5S2.5
[product_type] => holle plunjer
[product_return] => veer
)
);


it becomes this using array_values(), note the indexes per item:



Array(
[0] => Array(
[product_id] => 1
[product_model] => HFJ5G1.5
[product_type] => plat
[product_return] => graviteits
)
[1] => Array(
[product_id] => 2
[product_model] => HHJ5S2.5
[product_type] => holle plunjer
[product_return] => veer
)
);


then encoded to json and stored to jsonString:



jsonString = [
{
product_id: 1,
product_model: HFJ5G1.5,
product_type: plat,
product_return: graviteits
},
{
product_id: 2,
product_model: HHJ5S2.5,
product_type: holle plunjer,
product_return: veer
}
];

alert(jsonString.length);

[#87433] Tuesday, February 14, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
collinisaaka

Total Points: 194
Total Questions: 105
Total Answers: 104

Location: Tonga
Member since Tue, Nov 30, 2021
3 Years ago
;