Hello.

There is such a code

foreach($sett as $k=>$v){ foreach($v["funcsPole"] as $k1=>$v1){ if($v1=="")unset($v["funcsPole"][$k1]); } $tmp=json_encode($v); $db->Query("UPDATE `fields` SET params='".$tmp."' WHERE id=$k AND zone_id=$zone_id"); } 

The $ sett set is passed through the form, it has 6 values, all absolutely identical. But when encoding it in JSON It turns out this result:

 array(6) { [1]=> object(stdClass)#3 (4) { ["numPole"]=> string(4) "wera" ["namePole"]=> string(3) "asd" ["funcsPole"]=> array(4) { <- тут [0]=> string(5) "cam_4" [1]=> string(5) "cam_3" [2]=> string(5) "cam_4" [3]=> string(5) "cam_5" } ["priorPole"]=> string(2) "32" } [2]=> object(stdClass)#4 (4) { ["numPole"]=> string(3) "wer" ["namePole"]=> string(4) "werr" ["funcsPole"]=> object(stdClass)#5 (2) { <- тут ["0"]=> string(5) "cam_3" ["2"]=> string(5) "cam_4" } ["priorPole"]=> string(0) "" } 

That is, what is allocated (<- here), for the first value of the array is encoded as an array, and in the second value as an object. With what it can be connected?

The form has 6 sections, each section is passed as an element of the array

    3 answers 3

    The array elements are not consecutive, although the index is numeric, apparently, the encoder considers it safer to make an object out of it. if you need to always be the same, then use JSON_FORCE_OBJECT when encoding or true as the second parameter when decoding

    This example shows clearly what the problem is:

     <?php for ($i=0;$i<5;$i++) { $arr[]=$i; } $j1=json_encode($arr); unset($arr[3]); $j2=json_encode($arr); echo "$j1\n$j2\n-------\n"; print_r(json_decode($j1)); print_r(json_decode($j2)); echo "------\n"; print_r(json_decode($j1,true)); print_r(json_decode($j2,true)); 

    http://ideone.com/QVNxUc

    • Indeed the order of the elements are not consecutive. But is it possible in any case to convert this into an array, and not into an object? that is, how to make JSON encode in square brackets, not curly, regardless of the order of the indices? Just the funcsPole field (there are 4 of them) can fill out in a row. One of them may be empty to transmit. On the server, I exclude it and encode it. - Yoharny Babay

    The object is enclosed in braces {}. Between the name and value is the symbol ":", and the name / value pairs are separated by commas. The array (one-dimensional) is enclosed in square brackets []. This is a set of values ​​that have serial numbers (indices) and values ​​separated by commas.

    This is what I mean: can there be any differences in the design of the transmitted array? It would not be bad to take a look at the original $ sett option, before any of its transformations ...

      As it was said by other users, the whole thing is in the coding function. JSON prefers to turn an associative array into stdClass. If you want to replace it with associative arrays, then you should add a parameter with the JSON_FORCE_OBJECT constant. json_decode ($ json_str, JSON_FORCE_OBJECT);