php把数组保存数据库程序代码
我们在做缓存文件时经常会要把php代码或数组转换成字符串保存到数据库中,下面我来介绍两种把数组保存到数据库的方法。
方法一:用serialize写入,再用unserialize输出
serialize()就是将PHP中的变量如对象(object),数组(array)等等的值序列化为字符串后存储起来.序列化的字符串我们可以 存储在其他地方如数据库、Session、Cookie等,序列化的操作并不会丢失这些值的类型和结构。这样这些变量的数据就可以在PHP页面、甚至是不 同PHP程序间传递了。
而unserialize()就是把序列化的字符串转换回PHP的值。返回的是转换之后的值,可为 integer、float、string、array 或 object如果传递的字符串不可解序列化,则返回 FALSE,代码如下:
- class db {
- private $host;
- private $user;
- private $pwd;
- private $dbname;
- private $Mysqli;
- function __construct($host, $user, $pwd, $dbname) {
- $this->host = $host;
- $this->user = $user;
- $this->pwd = $pwd;
- $this->dbname = $dbname;
- $this->db();
- }
- function db() {
- $this->mysqli = new mysqli ( $this->host, $this->user, $this->pwd, $this->dbname );
- }
- function select() {
- $this->mysqli->query("SET CHARSET GBK");
- $sql = "SELECT id,cname FROM hdw_channel";
- $result = $this->mysqli
- ->query ( $sql );
- $rows = array ();
- while ( $row = $result->fetch_assoc () ) {
- $rows [] = $row;
- }
- ECHO "<PRE>";
- print_r ( $rows );
- }
- function __wakeup(){
- $this->db();
- }
- }
- $chanel = new db("localhost",'root','','hdcms');
-
- session_start();
- $_SESSION['channel_obj'] = serialize($chanel);
-
- class ren{
- private $name;
- private $age;
- function __construct($name,$age){
- $this->name =$name;
- $this->age = $age;
- }
- function show(){
- echo "姓名是:{$this->name} 年龄是:{$this->age}";
- }
- function __sleep(){
- return array_keys(get_object_vars($this));
- }
- }
- $zao = new ren("赵六",44);
- echo serialize($zao);
- ====================================
- session_start();
- include '59.php';
- $channel_obj=unserialize($_SESSION['channel_obj']);
- $channel_obj->select();
方法二:用json_encode写入,再用json_decode输出
json_encode之前,把所有数组内所有内容都用urlencode()处理一下,然用json_encode()转换成json字符串,最后再用urldecode()将编码过的中文转回来,代码如下:
- <?php
-
-
-
-
-
-
-
-
-
- function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
- {
- static $recursive_counter = 0;
- if (++$recursive_counter > 1000) {
- die('possible deep recursion attack');
- }
- foreach ($array as $key => $value) {
- if (is_array($value)) {
- arrayRecursive($array[$key], $function, $apply_to_keys_also);
- } else {
- $array[$key] = $function($value);
- }
-
- if ($apply_to_keys_also && is_string($key)) {
- $new_key = $function($key);
- if ($new_key != $key) {
- $array[$new_key] = $array[$key];
- unset($array[$key]);
- }
- }
- }
- $recursive_counter--;
- }
-
-
-
-
-
-
-
-
-
- function JSON($array) {
- arrayRecursive($array, 'urlencode', true);
- $json = json_encode($array);
- return urldecode($json);
- }
- $array = array
- (
- 'Name'=>'希亚',
- 'Age'=>20
- );
-
- echo JSON($array);
- ?>