PHP array to string writing method to database

Source: Internet
Author: User
Tags array to string eval

The simplest way

Convert implode

The code is as follows: Copy code

Array-> character
$ Txt = implode ("? ", Arr []);

Character> array
$ Arr [] = explode ("? ", Txt );

Use the serialize function of php.

Example:

The code is as follows: Copy code

$ Data = array ('Shanghai', 'Beijing', 'Wuhan ');
$ Data = serialize ($ data );
Echo $ data;

How can I convert the array string retrieved from the database into an array? Use the unserialize function:

The code is as follows: Copy code
$ Data = unserialize ($ data );
Echo $ data;

 
Of course, we can also directly write data to the file.

Serialize and unserialize.

The code is as follows: Copy code

<? Php
$ File = "./data/file. cache ";
$ Array = array ("count" => "3000 ",
& Quot; num & quot; = & quot; 300 & quot ");
// Cache
File_put_contents ($ file, serialize ($ array); // write cache
$ CacheArray = unserialize (file_get_contents ($ file ));
Print_r ($ cacheArray );
?>

Example

Eval functions of php during use

String2array, array2string PHP array to write strings to the database, string array to executable

The code is as follows: Copy code

/**
* Convert a string to an array
*
* @ Param string $ data string
* @ Return array returns the array format. If data is null, an empty array is returned.
*/
Function string2array ($ data ){
If ($ data = '') return array ();
@ Eval ("$ array = $ data ;");
Return $ array;
}  
/**
* Convert an array to a string
*
* @ Param array $ data array
* @ Param bool $ isformdata if it is 0, new_stripslashes is not used for processing. Optional. The default value is 1.
* @ Return string returns a string. If data is null, null is returned.
*/
Function array2string ($ data, $ isformdata = 1 ){
If ($ data = '') return '';
If ($ isformdata) $ data = new_stripslashes ($ data );
Return addslashes (var_export ($ data, TRUE ));

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.