phparraytoobject
⑴ 什麼是標量類型 php中的
數據類型分為:標量數據類型,復合數據類型,特殊數據類型1.標量數據類型:是數據結構中最基本單元,只能儲存一個數據,包括boolean,string,integer,float1.1string類型:定義字元串與三種方式:單引號(『)、雙引號(「)、界定符(<<<)單引號和雙引號是常使用定義方式,區別是雙引號中包含的變數會自動被替換成實際數值,而單引號包含的變數則按普通字元串輸出。<?php$i="welcome to network1024";echo '$i'; //將輸出$iecho "$i"; //輸出welcome to network1024?> 轉義字元:
序列 含義\n 換行\r 回車\t 水平製表符\\ 反斜線\\$ 符號$\』 符號』\」 符號」\[0-7]{1,3} 此正則表達式序列匹配一個用八進制符號表示的符號\x[0-9A-Fa-f]{1-2} 此正則表達式序列匹配一個用十六進制符號表示的符號注意:\n和\r在windows系統下沒區別,都可當回車符;Linux下\n表示游標回到行首,仍在本行,\r則換到下一行,卻不會回到行首。<?php$i=<<<network1024 //必須另起一行welcome to network1024network1024;echo "$i"; //輸出welcome to network1024?>1.2integer類型:32位系統范圍:-2147483648~2147483647,如果超出范圍發生整數溢出,當float處理,返回float類型;表示方式:十進制:123;八進制:0123;十六進制:0x123;1.3float類型:32位系統范圍:1.7E-308~1.7E+308表示方式:標准格式:3.141592654;科學計數法試:3141592654E-9注意:浮點數數值只是一個近似值,所以盡量避免浮點數間比較大小,因為最後的結果往往不準確。 2復合數據類型:包括數組array和對象object數組類型:是一個數據集合,可以包括多種數據:標量數據、數組、對象、資源、及PHP中支持的其他語法結構。數組中每個數據成為一個元素,元素包括索引(鍵名)和值兩部分。元素索引只能有數字或字元串組成。元素值可以是多種數據類型。數組索引自動編號從0開始語法格式:$array=(「value1」,」value2」……)或$array[key]=」value」或$array(key1=>value1,key2=value2……)<?php$network1024=array(1=>"how",2=>2,'are'=>"you");echo $network1024[2]; //輸出2echo $network1024[are]; //輸出you?>聲明數組後,數組中的元素個數可以自由更改。只要給數組賦值,數組就會自動增加長度。 3特殊類型:包括空值NULL和資源resourceresource:資源是由專門的函數來建立和使用的,它是一種特殊的數據類型,並由程序員分配。在使用資源時,要及時釋放不需要的資源。如果忘記釋放資源,系統自動啟動垃圾回收機制,避免內存消耗殆盡。NULL:表示變數沒有值。NULL不區分大小寫,null和NULL都是一樣。為NULL的情況:被賦為null;尚未被賦值;通過函數unset()而被銷毀。 4數據類型轉換:(type)value類型關鍵字 類型轉換 類型關鍵字 類型轉換(int),(integer) 轉換成整形 (array) 轉換成數組(float),(double),(real) 轉換成浮點型 (object) 轉換成對象(bool),(boolean) 轉換成浮點型 (string) 轉換成浮點型注意:轉換為boolean:null、0、未賦值的變數或數組會轉換為false,其他為true轉化為integer:boolean:false為0,true為1 float:小數部分被捨去 string:以數字開頭則截取到非數字位,否則輸出0 通過函數bool settpye(mixed var , string type)var為指定變數;type為要轉換的類型boolean/float/integer/string/array/null/objectsettype會改變變數自身類型
⑵ php toarray函數怎麼用
<?php
function object_to_array($obj){
$_arr = is_object($obj)? get_object_vars($obj) :$obj;
foreach ($_arr as $key => $val){
$val=(is_array($val)) || is_object($val) ? object_to_array($val) :$val;
$arr[$key] = $val;
}
return $arr;
⑶ PHP數組裡面存放對象
樓上解釋正確,不過我補充一下。
既然初始化是在類聲明之後,那麼可以通過手動串列化和反串列化來達到目的。
保存的時候使用serialize來保存,提取恢復的時候使用unserialize來恢復。
當然,這個還有一個要注意的地方,需要保存的對象最好是只包含數據,意思是,不要有資料庫連接資源、文件資源之類的,如果包含這些,串列和反串列的結果都是一個int 0,反串列的時候可能不能正常工作。
至於對象串列反串列的一些可定製的功能,可以參考幫助文檔的這個部分:
http://dk2.php.net/manual/zh/language.oop.magic-functions.php
通過定義魔術函數__sleep __wakeup來實現。
⑷ 哪位高手能詳解下 PHP session_set_save_handler() 。 往往會寫這樣一個類,搜索了寫答案,但不詳細
我有代碼。但是我的報錯。好像是配置文件哪兒沒弄對:
Warning: Unknown: Unknown session.serialize_handler. Failed to encode session object. in Unknown on line 0
類的代碼:
class session{
private static $handler=null;
private static $ip=null;
private static $lifetime=null;
private static $time=null;
private static function init($pdo){
self::$handler=$handler;
self::$ip = !empty($_SERVER["REMOTE_ADDR"])?$_SERVER["REMOTE_ADDR"]:unknown;
self::$lifetime=ini_get("session.gc_maxlifetime");
self::$time=time();
}
static function start(PDO $pdo){
self::init($pdo);
session_set_save_handler(
array(__CLASS__,"open"),
array(__CLASS__,"close"),
array(__CLASS__,"read"),
array(__CLASS__,"write"),
array(__CLASS__,"destroy"),
array(__CLASS__,"gc")
);
session_start();
}
public static function open($path,$name){
return true;
}
public static function close(){
return true;
}
public static function read($PHPSESSID){
$sql="select PHPSESSID,update_time,client_ip,data from session where PHPSESSID= ?";
$stmt=self::$handler->prepare($sql);
$stmt->execute(array($PHPSESSID));
if(!$result=$stmt->fetch(PDO::FETCH_ASSOC)){
return "";
}
if(self::$ip != $result['client_ip']){
self::destroy($PHPSESSID);
return "";
}
if(($result['update_time'] + self::$lifetime) < self::$time){
self::destroy($PHPSESSID);
return "";
}
return $result["data"];
}
public static function write($PHPSESSID,$data){
$sql="select PHPSESSID,update_time,client_ip,data from session where PHPSESSID= ?";
$stmt=self::$handler->prepare($sql);
$stmt->execute(array($PHPSESSID));
if($result=$stmt->fetch(PDO::FETCH_ASSOC)){
if($result["data"] != $data || self::$time > ($result['update_time']+30)){
$sql="update session set update_time=?,data=? where PHPSESSID=?";
$stmt=self::$handler->prepare($sql);
$stmt->execute(array(self::$time,$data,$PHPSESSID));
}
}else{
if(!empty($data)){
$sql="insert into session(PHPSESSID,update_time,client_ip,data values(?,?,?,?))";
$sth=self::$handler->prepare($sql);
$sth->execute(array($PHPSESSID,self::$time,self::$ip,$data));
}
}
return true;
}
public static function destroy($PHPSESSID){
$sql="delete from session where PHPSESSID=?";
$stmt=self::$handler->prepare($sql);
$stmt->execute(array($PHPSESSID));
return true;
}
public static function gc($lifetime){
$sql="delete from session where update_time < ?";
$stmt=self::$handler->prepare($sql);
$stmt->execute(array(self::$time-$lifetime));
return true;
}
}
try{
$pdo=new PDO("mysql:host=localhost;dbname=shoping","root","123456");
}catch(PDDException $e){
echo $e->getMessage();
}
session::start($pdo);
⑸ mongo php 操作 怎樣更新一條數據
PHP操作MongoDB資料庫的簡單示例。
Mongodb的常用操作
參看手冊,php官方的http://us2.php.net/manual/en/mongo.manual.php
也可以參看mongodb官方的教程。
一,Mognodb資料庫連接
1)、默認格式
復制代碼代碼示例:
$m=newMongo();
//這里採用默認連接本機的27017埠,當然也可以連接遠程主機如192.168.0.4:27017,如果埠是27017,埠可以省略。
2)、標准連接
$m=newMongo(「mongodb://${username}:${password}@localhost」);
實例:
復制代碼代碼示例:
$m=newMongo(「mongodb://127.0.0.1:27017/admin:admin」);
資料庫的用戶名和密碼都是admin
資料庫操作:
1)、插入數據:
復制代碼代碼示例:
<?php
//這里採用默認連接本機的27017埠,當然你也可以連接遠程主機如192.168.0.4:27017
//如果埠是27017,埠可以省略
$m=newMongo("mongodb://127.0.0.1:27017/admin:admin");
//選擇comedy資料庫,如果以前沒該資料庫會自動創建,也可以用$m->selectDB("comedy");
$db=$m->comedy;
//選擇comedy裡面的collection集合,相當於RDBMS裡面的表,也可以使用
$collection=$db->collection;
$db->selectCollection("collection");
/*********添加一個元素**************/
$obj=array("title"=>"php1","author"=>"BillWatterson");
//將$obj添加到$collection集合中
$collection->insert($obj);
/*********添加另一個元素**************/
$obj=array("title"=>"huaibei","online"=>true);
$collection->insert($obj);
//$query=array("title"=>"huaibei");
$query=array("_id"=>$obj['_id']);
$cursor=$collection->find($query);
//遍歷所有集合中的文檔
foreach($cursoras$obj){
echo$obj["title"]." ";
echo$obj["_id"]." ";
}
//斷開MongoDB連接
$m->close();
2)、帶條件的查詢
查詢title為huaibei的欄位
1$query=array(」title」=>」huaibei」);
2$cursor=$collection->find($query);//在$collectio集合中查找滿足$query的文檔
常用的SQL轉化為mongodb的條件
復制代碼代碼示例:
mysql:id=123
mongo:array(『id』=>123)
mysql:namelink』%bar%』
mongo:array(『name』=>newMongoRegex(『/.*bar.*/i』))
mysql:whereid>10
mongo:array(『id』=>array(『$gt』=>10))
mysql:whereid>=10
mongo:array(『id』=>array(『$gte』=>10))
mysql:whereid<10
mongo:array(『id』=>array(『$lt』=>10))
mysql:whereid<=10
mongo:array(『id』=>array(『$lte』=>10))
mysql:whereid>1andid<10
mongo:array(『id』=>array(『$gt』=>1,』$lt』=>10))
mysql:whereid<>10
mongo:array(『id』=>array(『$ne』=>10))
mysql:whereidin(123)
mongo:array(『id』=>array(『$in』=>array(1,2,3)))
mysql:whereidnotin(123)
mongo:array(『id』=>array(『$nin』=>array(1,2,3)))
mysql:whereid=2orid=9
mongo:array(『id』=>array(『$or』=>array(array(『id』=>2),array(『id』=>9))))
mysql:orderbynameasc
mongo:array(『sort』=>array(『name』=>1))
mysql:orderbynamedesc
mongo:array(『sort』=>array(『name』=>-1))
mysql:limit0,2
mongo:array(『limit』=>array(『offset』=>0,』rows』=>2))
mysql:selectname,email
mongo:array(『name』,'email』)
mysql:selectcount(name)
mongo:array(『COUNT』)//注意:COUNT為大寫
更詳細的轉換參考http://us2.php.net/manual/en/mongo.sqltomongo.php
注意事項:
查詢時,每個Object插入時都會自動生成一個獨特的_id,它相當於RDBMS中的主鍵,用於查詢時非常方便(_id每一都不同,很像自動增加的id)
例如:
復制代碼代碼示例:
<?php
$param=array("name"=>"joe");
$collection->insert($param);
$joe=$collection->findOne(array("_id"=>$param['_id']));
print_R($joe);
$m->close();
返回結果:Array([_id]=>MongoIdObject([$id]=>4fd30e21870da83416000002)[name]=>joe)
更改欄位值:
復制代碼代碼示例:
<?php
$sign=array("title"=>'php1');
$param=array("title"=>'php1','author'=>'test');
$joe=$collection->update($sign,$param);
刪除一個資料庫:
復制代碼代碼示例:
$m->dropDB(「comedy」);
列出所有可用資料庫:
復制代碼代碼示例:
$m->listDBs();//無返回值
附,mongodb常用的資料庫方法
MongoDB中有用的函數:
創建一個MongoDB對象
復制代碼代碼示例:
<?php
$mo=newMongo();
$db=newMongoDB($mo,』dbname』);//通過創建方式獲得一個MongoDB對象
刪除當前DB
復制代碼代碼示例:
<?php
$db=$mo->dbname;
$db->drop();
獲得當前資料庫名
復制代碼代碼示例:
<?php
$db=$mo->dbname;
$db->_tostring();
選擇想要的collection:
復制代碼代碼示例:
A:
$mo=newMongo();
$coll=$mo->dbname->collname;//獲得一個collection對象
B:
$db=$mo->selectDB(』dbname』);
$coll=$db->collname;
C:
$db=$mo->dbname;
$coll=$db->collname;
D:
$db=$mo->dbname;
$coll=$db->selectCollectoin(』collname』);//獲得一個collection對象
插入數據(MongoCollection對象):
http://us.php.net/manual/en/mongocollection.insert.php
MongoCollection::insert(array$a,array$options)
array$a要插入的數組
array$options選項
safe是否返回操作結果信息
fsync是否直接插入到物理硬碟
例子:
復制代碼代碼示例:
$coll=$mo->db->foo;
$a=array(』a』=>』b』);
$options=array(』safe』=>true);
$rs=$coll->insert($a,$options);
$rs為一個array型的數組,包含操作信息
刪除資料庫中的記錄(MongoCollection對象):
http://us.php.net/manual/en/mongocollection.remove.php
MongoCollection::remove(array$criteria,array$options)
array$criteria條件
array$options選項
safe是否返回操作結果
fsync是否是直接影響到物理硬碟
justOne是否隻影響一條記錄
例子:
復制代碼代碼示例:
$coll=$mo->db->coll;
$c=array(』a』=>1,』s』=>array(』$lt』=>100));
$options=array(』safe』=>true);
$rs=$coll->remove($c,$options);
$rs為一個array型的數組,包含操作信息
更新資料庫中的記錄(MongoCollection對象):
http://us.php.net/manual/en/mongocollection.update.php
MongoCollection::update(array$criceria,array$newobj,array$options)
array$criteria條件
array$newobj要更新的內容
array$options選項
safe是否返回操作結果
fsync是否是直接影響到物理硬碟
upsert是否沒有匹配數據就添加一條新的
multiple是否影響所有符合條件的記錄,默認隻影響一條
例子:
復制代碼代碼示例:
$coll=$mo->db->coll;
$c=array(』a』=>1,』s』=>array(』$lt』=>100));
$newobj=array(』e』=>』f』,』x』=>』y』);
$options=array(』safe』=>true,』multiple』=>true);
$rs=$coll->remove($c,$newobj,$options);
$rs為一個array型的數組,包含操作信息
查詢collection獲得單條記錄(MongoCollection類):
http://us.php.net/manual/en/mongocollection.findone.php
arrayMongoCollection::findOne(array$query,array$fields)
array$query條件
array$fields要獲得的欄位
例子:
復制代碼代碼示例:
$coll=$mo->db->coll;
$query=array(』s』=>array(』$lt』=>100));
$fields=array(』a』=>true,』b』=>true);
$rs=$coll->findOne($query,$fields);
如果有結果就返回一個array,如果沒有結果就返回NULL
查詢collection獲得多條記錄(MongoCollection類):
http://us.php.net/manual/en/mongocollection.find.php
MongoCursorMongoCollection::find(array$query,array$fields)
array$query條件
array$fields要獲得的欄位
例子:
復制代碼代碼示例:
$coll=$mo->db->coll;
$query=array(』s』=>array(』$lt』=>100));
$fields=array(』a』=>true,』b』=>true);
$cursor=$coll->find($query,$fields);
//排序
$cursor->sort(array(『欄位』=>-1));(-1倒序,1正序)
//跳過部分記錄
$cursor->skip(100);跳過100行
//只顯示部分記錄
$cursor->limit(100);只顯示100行
返回一個游標記錄對象MongoCursor。
針對游標對象MongoCursor的操作(MongoCursor類):
http://us.php.net/manual/en/class.mongocursor.php
循環或結果記錄:
復制代碼代碼示例:
$cursor=$coll->find($query,$fields);
while($cursor->hasNext()){
$r=$cursor->getNext();
var_mp($r);
}
或者
$cursor=$coll->find($query,$fields);
foreache($cursoras$k=>$v){
var_mp($v);
}
或者
$cursor=$coll->find($query,$fields);
$array=iterator_to_array($cursor);
⑹ php函數設定參數類型
functionsin($value)
{
if(!is_bool($value))
{
echo"Warning:Notabooleanvalue!";
return;
}
//用戶代碼
//用戶代碼
//用戶代碼
}
跟樓上大同小異!加了個return!
⑺ 新手求助高手解決 PHP數組轉換XML問題,研究好久都不行.
<?php
$team=array(
'id'=>'22955',
'video_order_id'=>'22955',
'is_audio'=>'0',
'status_format'=>'待審核',
'ftp_path'=>'2013/1374/5695/2479/137456952479.ssm/',
'lists'=>array(array('PreviewMTA'=>'A','PreviewMTB'=>'B')),
'lists1'=>array(array('PreviewMTA'=>'B'))
);
echosaveXML($team);
functionsaveXML($arr,$root='response'){
if(!preg_match('/[a-zA-Z][a-zA-Z0-9_]/',$root)){
$root='response';
}
$xml=newDOMDocument('1.0','UTF-8');
$xml->formatOutput=true;
$response=$xml->createElement($root);
$xml->appendChild($response);
foreach($arras$key=>$value){
if(is_array($value)){
$first=$xml->createElement($key);
_createElement($value,$first,$xml);
}else{
$first=$xml->createElement($key,$value);
}
$response->appendChild($first);
}
return$xml->saveXML();
//$xml->save('create_xml.xml');
}
function_createElement($arr,$parentDom,&$xml){
foreach($arras$value){
$list=$xml->createElement('list');
foreach($valueas$k=>$val){
if(is_array($val)){
$dom=$xml->createElement($k);
_createElement($val,$dom,$xml);
}else{
$dom=$xml->createElement($k,$val);
}
$list->appendChild($dom);
}
$parentDom->appendChild($list);
}
}
?>
可能和你要的結果有偏離
⑻ PHP中json_encode中文亂碼問題
php 中使用 json_encode() 內置函數(php > 5.2)可以使用得 php 中數據可以與其它語言很好的傳遞並且使用它。這個函數的功能是將數值轉換成json數據存儲格式
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
//結果
//{"a":1,"b":2,"c":3,"d":4,"e":5}
/*
下面看一款json_encode中文亂碼問題
解決方法是用urlencode()函數處理以下,在json_encode之前,把所有數組內所有內容都用urlencode()處理一下,然用json_encode()轉換成json字元串,最後再用urldecode()將編碼過的中文轉回來
*/
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--;
}
/**************************************************************
*
* 將數組轉換為json字元串(兼容中文)
* @param array $array 要轉換的數組
* @return string 轉換得到的json字元串
* @access public
*
*************************************************************/
function json($array) {
arrayrecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
$array = array
(
'name'=>'希亞',
'age'=>20
);
echo json($array);
//應用實例
$servname="localhost";
$sqlservname="root";
$sqlservpws="123456";
$sqlname="lock1";
$db=mysql教程_connect($servname,$sqlservname,$sqlservpws) or die("資料庫教程連接失敗");
mysql_select_db($sqlname,$db);
$sql = "select * from t_operater";
$result =mysql_query($sql);
$rows = mysql_num_rows($result);
while($obj = mysql_fetch_object($result))
{
$arr[] = $obj;
}
echo '({"total":"'.$rows.'","results":'.json_encode($arr).'})';
⑼ php中多維數組的問題
"Griffin"=>array()
表示索引"Griffin"是一個數組。=>可以簡單理解為賦值。這是php里特有的一種寫法。
數組分為2種,一種是自動索引數組。比如
$x=array ("Peter","Lois", "Megan");
那麼$X[0]值為"peter",$X[1]為lois。
還有一種是自定義索引數組。
比如
$x=array ("father"=>"Peter","mother"=>"Lois","son"=> "Megan");
那麼$x["father"] 就為"peter"
用引號圍起來表示這是一個索引字元串值。通常情況下你直接[Griffin]也可以。
但是如果你在系統里有一個變數
$Griffin="son";
那麼$families[Griffin]實際上會等於$families['son']。所以最好用引號圍起來。
更多詳細可以看php手冊數組一章。
==========================================================
數組
PHP 中的 數組 實際上是一個有序映射。映射是一種把 values 關聯到 keys 的類型。此類型在很多方面做了優化,因此可以把它當成真正的數組,或列表(向量),散列表(是映射的一種實現),字典,集合,棧,隊列以及更多可能性。數組元素的值也可以是另一個數組。樹形結構和多維數組也是允許的。
解釋這些結構超出了本手冊的范圍,但對於每種結構至少會提供一個例子。要得到這些結構的更多信息,建議參考有關此廣闊主題的其它著作。
語法
定義數組 array()
可以用 array() 語言結構來新建一個 array。它接受任意數量用逗號分隔的 鍵(key) => 值(value) 對。
array( key => value
, ...
)
// 鍵(key) 可是是一個 整數(integer) 或 字元串(string)
// 值(value) 可以是任意類型的值<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
key 可以是 integer 或者 string。如果key是一個 integer 的標准表示,則被解釋為整數(例如 "8" 將被解釋為 8,而 "08" 將被解釋為 "08")。key 中的浮點數被取整為 integer。在 PHP 中索引數組與關聯 數組 是相同的,它們都可以同時包含 整型 和 字元串 的下標。
值可以是任意的 PHP 類型。
<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
echo $arr["somearray"][6]; // 5
echo $arr["somearray"][13]; // 9
echo $arr["somearray"]["a"]; // 42
?>
如果對給出的值沒有指定鍵名,則取當前最大的整數索引值,而新的鍵名將是該值加一。如果指定的鍵名已經有了值,則該值會被覆蓋。
<?php
// 這個數組與下面的數組相同 ...
array(5 => 43, 32, 56, "b" => 12);
// ...
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
Warning
自 PHP 4.3.0 起,上述的索引生成方法改變了。如今如果給一個當前最大鍵名是負值的數組添加一個新值,則新生成的的索引將為零(0)。以前新生成的索引為當前最大索引加一,和正值的索引相同。
使用 TRUE 作為鍵名將使 integer 1 成為鍵名。使用 FALSE 作為鍵名將使 integer 0 成為鍵名。使用 NULL 作為鍵名將等同於使用空字元串。使用空字元串作為鍵名將新建(或覆蓋)一個用空字元串作為鍵名的值,這和用空的方括弧不一樣。
不能用數組和對象作為鍵(key)。這樣做會導致一個警告:Illegal offset type。
用方括弧的語法新建/修改
可以通過明示地設定值來改變一個現有的數組。
這是通過在方括弧內指定鍵名來給數組賦值實現的。也可以省略鍵名,在這種情況下給變數名加上一對空的方括弧(「[]」)。
$arr[key] = value;
$arr[] = value;
// key 可以是 integer 或 string
// value 可以是任意類型的值如果 $arr 還不存在,將會新建一個。這也是一種定義數組的替換方法。要改變一個值,只要給它賦一個新值。如果要刪除一個鍵名/值對,要對它用 unset()。
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
Note:
如上所述,如果給出方括弧但沒有指定鍵名,則取當前最大整數索引值,新的鍵名將是該值 + 1。如果當前還沒有整數索引,則鍵名將為 0。如果指定的鍵名已經有值了,該值將被覆蓋。
注意這里所使用的最大整數鍵名不一定當前就在數組中。它只要在上次數組重新生成索引後曾經存在過就行了。以下面的例子來說明:
<?php
// 創建一個簡單的數組
$array = array(1, 2, 3, 4, 5);
print_r($array);
// 現在刪除其中的所有元素,但保持數組本身不變:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);
// 添加一個單元(注意新的鍵名是 5,而不是你可能以為的 0)
$array[] = 6;
print_r($array);
// 重新索引:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>
以上常式會輸出:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
)
Array
(
[5] => 6
)
Array
(
[0] => 6
[1] => 7
)
實用函數
有很多操作數組的函數,參見數組函數一節。
Note:
unset() 函數允許刪除數組中的某個鍵。但要注意數組將不會重建索引。 If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.
<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will proce an array that would have been defined as
$a = array(1 => 'one', 3 => 'three');
and NOT
$a = array(1 => 'one', 2 =>'three');
*/
$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>
foreach 控制結構是專門用於數組的。它提供了一個簡單的方法來遍歷數組。
數組做什麼和不做什麼
為什麼 $foo[bar] 錯了?
應該始終在用字元串表示的數組索引上加上引號。例如用 $foo['bar'] 而不是 $foo[bar]。但是為什麼 $foo[bar] 錯了呢?可能在老的腳本中見過如下語法:
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>
這樣是錯的,但可以正常運行。那麼為什麼錯了呢?原因是此代碼中有一個未定義的常量(bar)而不是字元串('bar'-注意引號),而 PHP 可能會在以後定義此常量,不幸的是你的代碼中有同樣的名字。它能運行,是因為 PHP 自動將裸字元串(沒有引號的字元串且不對應於任何已知符號)轉換成一個其值為該裸字元串的正常字元串。例如,如果沒有常量定義為 bar,PHP 將把它替代為 'bar' 並使用之。
Note: 這並不意味著總是給鍵名加上引號。用不著給鍵名為常量或變數的加上引號,否則會使 PHP 不能解析它們。
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "\nChecking $i: \n";
echo "Bad: " . $array['$i'] . "\n";
echo "Good: " . $array[$i] . "\n";
echo "Bad: {$array['$i']}\n";
echo "Good: {$array[$i]}\n";
}
?>
以上常式會輸出:
Checking 0:
Notice: Undefined index: $i in /path/to/script.html on line 9
Bad:
Good: 1
Notice: Undefined index: $i in /path/to/script.html on line 11
Bad:
Good: 1
Checking 1:
Notice: Undefined index: $i in /path/to/script.html on line 9
Bad:
Good: 2
Notice: Undefined index: $i in /path/to/script.html on line 11
Bad:
Good: 2
演示此行為的更多例子:
<?php
// Show all errors
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// Correct
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Incorrect. This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// This defines a constant to demonstrate what's going on. The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');
// Notice the difference now
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]"; // Hello apple
// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>
當打開 error_reporting 來顯示 E_NOTICE 級別的錯誤(例如將其設為 E_ALL)時將看到這些錯誤。默認情況下 error_reporting 被關閉不顯示這些。
和在語法一節中規定的一樣,在方括弧(「[」和「]」)之間必須有一個表達式。這意味著可以這樣寫:
<?php
echo $arr[somefunc($bar)];
?>
這是一個用函數返回值作為數組索引的例子。PHP 也可以用已知常量,可能之前已經見過
<?php
$error_descriptions[E_ERROR] = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE] = "This is just an informal notice";
?>
注意 E_ERROR 也是個合法的標識符,就和第一個例子中的 bar 一樣。但是上一個例子實際上和如下寫法是一樣的:
<?php
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>
因為 E_ERROR 等於 1, 等等.
那麼為什麼這樣做不好?
也許有一天,PHP 開發小組可能會想新增一個常量或者關鍵字,或者用戶可能希望以後在自己的程序中引入新的常量,那就有麻煩了。例如已經不能這樣用 empty 和 default 這兩個詞了,因為他們是保留字。
Note: 重申一次,在雙引號字元串中,不給索引加上引號是合法的因此 "$foo[bar]"是合法的(「合法」的原文為valid。在實際測試中,這么做確實可以訪問數組的該元素,但是會報一個常量未定義的notice。無論如何,強烈建議不要使用$foo[bar]這樣的寫法,而要使用$foo['bar']來訪問數組中元素。--haohappy注)。至於為什麼參見以上的例子和字元串中的變數解析中的解釋。
轉換為數組
對於任意類型: integer, float, string, boolean and resource,如果將一個值轉換為數組,將得到一個僅有一個元素的數組(其下標為 0),該元素即為此標量的值。換句話說, (array)$scalarValue 與 array($scalarValue) 完全一樣。
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:
<?php
class A {
private $A; // This will become '\0A\0A'
}
class B extends A {
private $A; // This will become '\0B\0A'
public $AA; // This will become 'AA'
}
var_mp((array) new B());
?>
The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.
將 NULL 轉換到 數組(array) 會得到一個空的數組。
比較
可能使用 array_diff() 和數組運算符來比較數組。
Examples
PHP 中的數組類型有非常多的用途,因此這里有一些例子展示數組的完整威力。
<?php
// This:
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // key will be 0
);
$b = array('a', 'b', 'c');
// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // key will be 0
$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>
Example #1 Using array()
<?php
// Array as (property-)map
$map = array( 'version' => 4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);
// strictly numerical keys
$array = array( 7,
8,
0,
156,
-10
);
// this is the same as array(0 => 7, 1 => 8, ...)
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
// empty array
$empty = array();
?>
Example #2 集合
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as $color) {
echo "Do you like $color?\n";
}
?>
以上常式會輸出:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
直接改變數組的值在 PHP 5 中可以通過引用傳遞來做到。之前的版本需要需要採取變通的方法:
Example #3 集合
<?php
// PHP 5
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */
// Workaround for older versions
foreach ($colors as $key => $color) {
$colors[$key] = strtoupper($color);
}
print_r($colors);
?>
以上常式會輸出:
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
本例生成一個下標從1開始的數組。This example creates a one-based array.
Example #4 下標從1開始的數組
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
以上常式會輸出:
Array
(
[1] => 'January'
[2] => 'February'
[3] => 'March'
)
Example #5 填充數組
<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>
數組是有序的。也可以使用不同的排序函數來改變順序。更多信息參見數組函數。可以用 count() 函數來數出數組中元素的個數。
Example #6 數組排序
<?php
sort($files);
print_r($files);
?>
因為數組中的值可以為任意值,也可是另一個數組。這樣可以產生遞歸或多維數組。
Example #7 遞歸和多維數組
<?php
$fruits = array ( "fruits" => array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);
// Some examples to address values in the array above
echo $fruits["holes"][5]; // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]); // remove "first"
// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>
數組(Array) 的賦值總是會涉及到值的拷貝。使用 引用操作符 通過引用來拷貝數組。
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>