convert array to string and get it back to array in PHP

前端 未结 2 612
情深已故
情深已故 2021-01-23 09:25

I\'m using the Serialize function to store an array in my MYSQL database, and then I\'m unSerialize Him in other page. The array structure look like this :

Array         


        
2条回答
  •  抹茶落季
    2021-01-23 10:02

    The opposite of serialize is unserialize.

    $old_array = unserialize($serialized_array_string_from_db);
    

    Storing values serialized into the database, disallows to query them individually. You have to fetch the serialized value, unserialize and then you can start working with them. This is not very efficient from a database design perspective. My suggestion is to create individual fields for "names" and "rating" in a extra table.


    Store Array serialized to Database

    $array = array('names' => 'somename1', 'rating' => 10);
    $array_serialized_to_string = serialize($array);
    doStoreToDb($array_serialized_to_string, somewhere);
    

    Fetch Serialized Array from Database

    $array_serialized_to_string = doFetchFromDb(somewhere);
    $array = unserialize($array_serialized_to_string);
    

    The difference in array structure might be the result from querying "the return set as array". Just remove the outer array:

    $old_array = unserialize($serialized_array_string_from_db);
    $array = $old_array[0];
    

提交回复
热议问题