php把數組保存數據庫程序代碼
來源:程序員人生 發布時間:2013-12-07 20:00:06 閱讀次數:4587次
我們在做緩存文件時經常會要把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);
- ?>
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈