Json and multidimensional array

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 json using

 json_encode($array); 

The given 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 a warning (jsonString.length); result 4 But I want the result to be 2 in the morning, I was doing something wrong.

+4
source share
2 answers

object literal does not have .length

you can read 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 did not have numeric indices (starting at 0), it suggested that you used an associative array, so they dumped the element object, not the element array.

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

 json_encode(array_values($array)); 

then json will be an array .. then you can use the 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 like this using array_values ​​(), pay attention to the indices for the element:

 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 in json and stored in 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); 
+6
source

Objects do not support the length property: alert({}.length); It gives undefined and alert([].length); gives 0 . To find the "length" of the top level, you can do this as follows:

 var arr ={"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"}}; var len = 0; for(var i in arr) len++; alert(len); 

http://jsfiddle.net/uszaV/

+1
source

Source: https://habr.com/ru/post/1396773/


All Articles