Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwanted array indexes when using JSON.stringify

I use JSON.stringify method to pass an array to server.

I have an array that has 4 elements:

arr[10] = 1;
arr[20] = 1;
arr[30] = 1;
arr[40] = 1;

Then i do this:

arr = JSON.stringify(arr);

Then send it to the server:

                jQuery.ajax({
                    type: "post",
                    url: baseurl+"profile/mprofile/action/ratings/add_ratings",
                    data:{"checkbox":checkbox,"review":review,"speciality":speciality,"arr":arr},
                    success: function(data, status) {  

                        jQuery('#header-error').html(data);
                    } 
                }); 

I am getting the array in PHP with:

    $arr = $this->ci->input->post('arr');
    $arr = json_decode($arr);
    print_r($arr) ; die ;

the result is

Array
(
    [0] => 
    [1] => 
    [2] => 
    [3] => 
    [4] => 
    [5] => 
    [6] => 
    [7] => 
    [8] => 
    [9] => 
    [10] => 1
    [11] => 
    [12] => 
    [13] => 
    [14] => 
    [15] => 
    [16] => 
    [17] => 
    [18] => 
    [19] => 
    [20] => 1
    [21] => 
    [22] => 
    [23] => 
    [24] => 
    [25] => 
    [26] => 
    [27] => 
    [28] => 
    [29] => 
    [30] => 1
    [31] => 
    [32] => 
    [33] => 
    [34] => 
    [35] => 
    [36] => 
    [37] => 
    [38] => 
    [39] => 
    [40] => 1
)

Why is this happening?

like image 859
Kanishka Panamaldeniya Avatar asked Dec 01 '25 13:12

Kanishka Panamaldeniya


2 Answers

That's how javascript arrays work. When you set value to an index that is out of range, array is expanded, value is successfully set and all 'missing' values are set to undefined.

You are spoiled by PHP behaviour that blends the difference between arrays and dictionaries (or "associative arrays", in PHP talk).

To avoid this behaviour, just create a dictionary in javascript instead of array.

var arr = {};
arr[10] = 1;
arr[20] = 2;

Also, on PHP side you should pass true as a second parameter to json_decode.

json_decode($arr, true)

This will make it return array instead of stdclass.

like image 150
Sergio Tulentsev Avatar answered Dec 04 '25 05:12

Sergio Tulentsev


How do you initialize arr? You probably want to use an object instead of an Array. For example:

var arr = {};
arr[10] = 1;
arr[20] = 1;
arr[30] = 1;
arr[30] = 1;
var jsonified = JSON.stringify(arr);
console.log(jsonified);
like image 26
StevenLooman Avatar answered Dec 04 '25 06:12

StevenLooman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!