当前位置:首页 » 编程语言 » phparraytoobject

phparraytoobject

发布时间: 2023-06-07 13:05:55

⑴ 什么是标量类型 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
?>

热点内容
脚本精灵要root吗 发布:2025-02-14 05:51:30 浏览:211
安卓手机如何录屏怎么去掉触摸显示 发布:2025-02-14 05:36:23 浏览:995
安卓系统新品推荐怎么关 发布:2025-02-14 05:35:44 浏览:887
虚拟存储器的基础是 发布:2025-02-14 05:32:24 浏览:515
androidstudio出错 发布:2025-02-14 05:32:14 浏览:304
面容id存储多张脸 发布:2025-02-14 05:31:30 浏览:655
网站源码百度云 发布:2025-02-14 05:30:53 浏览:213
我得世界星际方块服务器ip 发布:2025-02-14 05:23:03 浏览:939
动态库什么时候不需要重新编译 发布:2025-02-14 05:18:56 浏览:13
android网络存储数据 发布:2025-02-14 05:03:19 浏览:130