生活随笔
收集整理的這篇文章主要介紹了
PHP将数组存入数据库中的四种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近突然遇到了一個問題,如何用PHP將數組存入到數據庫中,經過自己的多方查找和研究,總結了以下四種方法:
1.implode()和explode()方式
2.print_r()和自定義函數方式
3.serialize()和unserialize()方式
4.json_encode()和json_decode()方式
?
<?php// 將數組存入數據庫中的四種方式//1.implode和explode方式//2.print_r和自定義函數方式//3.serialize和unserialize方式//4.json_encode和json_decode方式// 如果想運行該文件,需要建立數據庫admin,和數據表test,或者修改代碼// //---------------------------------------------------------------// CREATE TABLE `test` (// `id` int(10) unsigned NOT NULL AUTO_INCREMENT key,// `array` text,// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;//定義用print_r將數組存儲到數據庫中的類header('content-type:text/html; charset=utf8');define("DB_HOST","localhost");define("DB_USER","root");define("DB_PWD","0227");define("DB_DBNAME","admin");define("DB_CHARSET","utf8");// 定義逆置print_r值的類
class Trie {protected $dict = array();protected $buf = '';function set($word, $value='') {if(is_array($word)) foreach($word as $k=>$v) $this->set($k, $v);$p =& $this->dict;foreach(str_split($word) as $ch) {if(! isset($p[$ch])) $p[$ch] = array();$p =& $p[$ch];}$p['val'] = $value;return $this;}function parse($str) {$this->doc = $str;$this->len = strlen($str);$i = 0;while($i < $this->len) {$t = $this->find($this->dict, $i);if($t) {$i = $t;$this->buf = '';}else $this->buf .= $this->doc{$i++};}}protected function find(&$p, $i) {if($i >= $this->len) return $i;$t = 0;$n = $this->doc{$i};if( isset($p[$n]) ) $t = $this->find($p[$n], $i+1);if($t) return $t;if( isset($p['val']) ) {$ar = explode(',', $p['val']);call_user_func_array( array($this, array_shift($ar)), $ar );return $i;}return $t;}function __call($method, $param) {echo "****\n$this->buf 未定義方法:$method 參數:" . join(',', $param) . "<br />\n";}
}class App extends Trie {public $res = array();protected $stack = array();protected $keyname = '';protected $buf = '';function __construct() {$this->stack[] =& $this->res;}protected function group() {if(! $this->keyname) return;$cnt = count($this->stack) - 1;$this->stack[$cnt][$this->keyname] = array();$this->stack[] =& $this->stack[$cnt][$this->keyname];$this->keyname = '';}protected function brackets($c) {$cnt = count($this->stack) - 1;switch($c) {case ')':if($this->keyname) $this->stack[$cnt][$this->keyname] = trim($this->buf);$this->keyname = '';array_pop($this->stack);break;case '[':if($this->keyname) $this->stack[$cnt][$this->keyname] = trim($this->buf);break;case ']':$this->keyname = $this->buf;}$this->buf = '';}
}
//類結束
//
//
//連接數據庫function connect(){$link = @mysql_connect(DB_HOST,DB_USER,DB_PWD) or die("數據庫連接失敗ERR:".mysql_errno().":".mysql_error());mysql_select_db(DB_DBNAME) or die("打開數據庫失敗");//mysql_errno()即顯示錯誤數量;mysql_error()即顯示錯誤信息;$sql = 'set names '.DB_CHARSET;mysql_query($sql) or die ("設置字符集失敗");return $link;}
//插入數據庫函數function insert($table, $array){$keys = join(",",array_keys($array));$vals = "'".join("','",array_values($array))."'";$sql = "insert {$table}({$keys})values({$vals})";mysql_query($sql);return mysql_insert_id();}//提取剛剛插入的數據function select($table){$sql = "select array from {$table} order by id desc";if($result = mysql_query($sql)){$values = mysql_fetch_assoc($result); $value = array_pop($values);}else{echo '提取失敗';}return $value;}//implode方式 一維數組可以,二維數組不可以,并且關聯數組無效function plode($table,$arr){echo '<h3 style="color:red"><b>implode</b>方式<br/>原數組,未插入前:</h3>';var_dump($arr);$str = addslashes(implode(",", $arr));$insert = array('id'=>'','array'=>$str);if(insert($table,$insert)){echo "插入成功.<br/>";}else{echo "插入失敗";exit;}$value = select($table);echo '<h3 style="color:red"><插入的內容:></h3>';var_dump($value);$explode = explode(",",$value);echo '<h3 style="color:red"><最終提取后處理的內容:></h3>';var_dump($explode);}// print_r方式function printR($table,$arr){echo '<h3 style="color:red"><b>print_r方式</b><br/>原數組,未插入前:></h3>';var_dump($arr);$print = addslashes(print_r($arr, true));$insert = array('id'=>'','array'=>$print);insert($table,$insert);$value = select($table);echo '<h3 style="color:red"><插入的內容:></h3>';var_dump($value);
$p = new App;
$p->set('Array','group')->set('[','brackets,[')->set('] =>','brackets,]')->set(')','brackets,)');
$p->parse($value);echo '<h3 style="color:red"><最終提取后處理的內容:></h3>';var_dump($p->res);}// serialize方式
function serial($table,$arr){echo '<h3 style="color:red"><b>serialize</b>方式<br/>原數組,未插入前:</h3>';var_dump($arr);$serialize = addslashes(serialize($arr));$insert = array('id'=>'','array'=>$serialize);insert($table,$insert);$value = select($table);echo '<h3 style="color:red"><方式插入數據庫中的內容:></h3>';var_dump($value);$serialize = unserialize($value);echo '<h3 style="color:red"><最終提取后處理的內容:></h3>';var_dump($serialize);
}
//json方式
function json($table,$arr){echo '<h3 style="color:red"><b>json_encode</b>方式<br/>原數組,未插入前:</h3>';var_dump($arr);$enjson = addslashes(json_encode($arr));$insert = array('id'=>'','array'=>$enjson);insert($table,$insert);$value = select($table);echo '<h3 style="color:red"><方式插入數據庫中的內容:></h3>';var_dump($value);$deunjson = json_decode($value,true);echo '<h3 style="color:red"><最終提取后處理的內容:></h3>';var_dump($deunjson);
}
// 執行函數//函數end?>
<form action="" method="get">
<select name="kind"><option value="1">一維數組</option><option value="2">二維數組</option></select>
<select name="id"><option value="1">implode方式</option><option value="2">print_r方式</option><option value="3">serialize方式</option><option value="4">json_encode方式</option></select>
<input type="submit" value="提交" name="submit">
</form>
<?phpif(!empty($_GET['submit'])){$kind = $_GET['kind'];$id = $_GET['id'];}else{echo "請選擇后按提交鍵";exit;}connect();
$ar1 =array('abcd'=>"sdfasdf",'bbb'=>'lxg','ccc'=>'bbbbbbbbb');//定義一個一維數組
$ar2 = array('a'=>$ar1,'b'=>$ar1); //二維數組
$table = "test";//使用的數據表if($kind=='1'){$arr = $ar1;
}else{$arr = $ar2;
}
switch ($id) {case '1':# code...plode($table, $arr);break;case '2':printR($table,$arr);break;case '3':serial($table,$arr);break;case '4':json($table,$arr);break;default:break;}?>
1.implode方式結果:
一維數組:
二維數組:報錯
2.print_r方式
一維數組:
二維數組:
3.serialize方式:
一維數組:
二維數組:
4.json方式
一維數組:
二維數組:
以
上幾種方法從插入數據庫的數據大小來看json方式最好,該演示中沒有使用中文,如果將數組改成中文你會發現json的強大之處,第一種方式無法將多維數組存入數據庫中,第二種方式還要用自定義類,推薦使用第三種和第四種方式!
總結
以上是生活随笔為你收集整理的PHP将数组存入数据库中的四种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。