PHP adds keys to decoded and then encoded JSON data

后端 未结 2 858
醉酒成梦
醉酒成梦 2020-12-04 03:22

I\'m not sure why this is happening, but I seem to run into this problem often. Here is my original JSON for a shopping cart:

{
    \"cartitems\": [
                 


        
2条回答
  •  一生所求
    2020-12-04 03:58

    In PHP, there are only arrays, which are used for both associative and numerically indexed maps/lists/arrays. Javascript/JSON has two distinct concepts: numerically indexed arrays ([...]) and object maps ({ foo : ... }). For PHP's json_encode to decide which to use when encoding an array, there's some logic behind the scenes. Generally, if the array keys are contiguous and all numerical, the array is encoded to a JSON array ([...]). If there's even one key out of order or a non-numeric key, a JSON object is used instead.

    Why your array manipulation in particular triggers an object, I don't know. To avoid this though, you can reset your array keys to make sure they're numerically, contiguously indexed:

    $_SESSION['cart_items']['cartitems'] = array_values($_SESSION['cart_items']['cartitems']);
    

提交回复
热议问题