convert array to string and get it back to array i

2020-04-19 21:24发布

问题:

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 ( [0] => Array ( [names] => somename1 [rating] => 10 ) [1] => Array ( [names] => somename2 [rating] => 9 ) )

When I INSERT the array to the database I'm using this function to convert it to string :

$array_string=mysql_escape_string(serialize($arr));

And then, when I'm doing the unSerialize, I don't know how to restore the string(array in the database) to the exactly structure that it was before. (how to convers this string back to array)

I know I have to use this line :

$arr=explode("|",$list);

In some way, but I can't restore it to the exactly structure of the array it was before. The result of this line is a little bit different in the structure of the array :

Array ( [0] => Array( [0] => Array ( [names] => d [rating] => 7 ) [1] => Array ( [names] => b [rating] => 6 )  ) )

Thanks

回答1:

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];


回答2:

Try json_encode and json_decode

$array_to_store = array(....);
$str_array = json_encode($array_to_store);
//Store $str_array
//Retrieve it and to make it an array again
$array = json_decode($str_array, true);

******************* Edited *********************

I do not see what is wrong with serialize and unserialize:

$array = array(
        array(
                'names' => 'somename1',
                'rating' => 10
             ),
        array(
                'names' => 'somename2',
                'rating' => 9
             )
    );

//Array before
print_r('<pre>');
print_r($array);

//Serialised Array
$s = serialize($array);

print_r('<pre>');
print_r($s);

//Unserialised Array
print_r('<pre>');
print_r(unserialize($s));