Removing array index reference when using json_encode()

后端 未结 3 2075
不知归路
不知归路 2020-11-27 19:08

I have made a small application using jQuery\'s datepicker. I am setting unavailable dates to it from a JSON file which looks like this:

{ \"dat         


        
相关标签:
3条回答
  • 2020-11-27 19:16

    Use array_values() for your issue:

    $arr['dates'] = array_values($arr['dates']);
    //..
    $arr = json_encode($arr);
    

    Why? Because you're unsetting array's key without re-ordering it. So after this the only way to keep that in JSON will be encode keys too. After applying array_values(), however, you'll get ordered keys (starting from 0) which can be encoded properly without including keys.

    0 讨论(0)
  • 2020-11-27 19:21

    In Laravel collections(just in case) you can do

        $newArray = $collection->values()->toArray();
    

    or

        $jsonEncoded = $collection->values()->toJson();
    
    0 讨论(0)
  • 2020-11-27 19:23

    You are ignoring the return value of array_values in your existing attempt to reindex the array. Correct is

    $arr['dates'] = array_values($arr['dates']);
    

    The reindexing should also be moved outside the foreach loop, there is no point in reindexing multiple times.

    0 讨论(0)
提交回复
热议问题