Preferred method to store PHP arrays (json_encode vs serialize)

前端 未结 20 2284
孤独总比滥情好
孤独总比滥情好 2020-11-22 05:55

I need to store a multi-dimensional associative array of data in a flat file for caching purposes. I might occasionally come across the need to convert it to JSON for use in

20条回答
  •  野的像风
    2020-11-22 06:24

    Before you make your final decision, be aware that the JSON format is not safe for associative arrays - json_decode() will return them as objects instead:

    $config = array(
        'Frodo'   => 'hobbit',
        'Gimli'   => 'dwarf',
        'Gandalf' => 'wizard',
        );
    print_r($config);
    print_r(json_decode(json_encode($config)));
    

    Output is:

    Array
    (
        [Frodo] => hobbit
        [Gimli] => dwarf
        [Gandalf] => wizard
    )
    stdClass Object
    (
        [Frodo] => hobbit
        [Gimli] => dwarf
        [Gandalf] => wizard
    )
    

提交回复
热议问题