php取出数组单个值的方法

yipeiwu_com5年前PHP代码库

1.数组arr

var_dump(arr) 值如下:

array (size=3)
 'delete' => 
 array (size=3)
  0 => string 'HBSFlyRecode20170222-101501.txt' (length=31)
  1 => string 'HBSFlyRecode20170222-105502.txt' (length=31)
  2 => string 'HBSFlyRecode20170222-108803.txt' (length=31)
 'new' => 
 array (size=3)
  0 => string 'HBSFlyRecode20170223-101504.txt' (length=31)
  1 => string 'HBSFlyRecode20170223-105505.txt' (length=31)
  2 => string 'HBSFlyRecode20170223-108806.txt' (length=31)
 'old' => 
 array (size=3)
  0 => string 'HBSFlyRecode20170221-101507.txt' (length=31)
  1 => string 'HBSFlyRecode20170221-105508.txt' (length=31)
  2 => string 'HBSFlyRecode20170221-108809.txt' (length=31)
echo $arr['old'][0];
打印出: HBSFlyRecode20170221-101507.txt

但是如果arr是对象形式 , 打印结果如下:

var_dump(arr)
object(stdClass)[1]
 public 'delete' => 
 array (size=3)
  0 => string 'HBSFlyRecode20170222-101501.txt' (length=31)
  1 => string 'HBSFlyRecode20170222-105502.txt' (length=31)
  2 => string 'HBSFlyRecode20170222-108803.txt' (length=31)
 public 'new' => 
 array (size=3)
  0 => string 'HBSFlyRecode20170223-101504.txt' (length=31)
  1 => string 'HBSFlyRecode20170223-105505.txt' (length=31)
  2 => string 'HBSFlyRecode20170223-108806.txt' (length=31)
 public 'old' => 
 array (size=3)
  0 => string 'HBSFlyRecode20170221-101507.txt' (length=31)
  1 => string 'HBSFlyRecode20170221-105508.txt' (length=31)
  2 => string 'HBSFlyRecode20170221-108809.txt' (length=31)

就不能使用 $arr[‘old'][0] 取值了 , 可以使用arr对象和数组通用的foreach方式取值:

function getValue($arr){
 foreach($arr as $key => $value){
  if(is_array($value)){
   getValue($value);
  }else{
   echo $value."<br>";
  }
 }
}

如果arr为对象形式 , 可以考录将对象转为数组形式 , 这里提供一种快捷方式:

1. $object_json = json_encode($arr);得到的是对象

$json = json_encode($arr,true);得到的是纯json

2. json_decode($object_json) 和 json_decode($json)得到的是数组对象

json_decode($object_json,true) 和 json_decode($json,true)得到的是数组

综上 , 可以将数组对象转为数组的方式:

arr=jsondecode(jsonencode(arr=jsondecode(jsonencode(arr,true),true);

项目中发现此问题 , 建议大家在php中将json和array转换时 , json_encode() 和 json_decode()的第二个参数要加 true , 即:

json_encode(arr,true);jsondecode(arr,true);jsondecode(json,true); 

以上这篇php取出数组单个值的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【宜配屋www.yipeiwu.com】。

相关文章

php压缩HTML函数轻松实现压缩html/js/Css及注意事项

压缩HTML的起因 如何提高网页加载速度 ,需要怎么对html页面优化相信是每个拟提高建站技术站长曾想到的问题,其实网页优化的方法还是很多。 有童鞋询问higrid如何 压缩HTML,也...

php技巧小结【推荐】

1 如何定义linux和window通用的文件分隔符号 DIRECTORY_SEPARATOR : 目录分隔符,是定义php的内置常量。在调试机器上,在windows我们习惯性的使用“\...

php数据访问之查询关键字

php数据访问之查询关键字

本文实例为大家分享了php查询操作的实现代码,供大家参考,具体内容如下 一、一个关键字查询 主页面: <html> <head> <meta http...

两个php日期控制类实例

本文实例讲述了两个php日期控制类。分享给大家供大家参考。具体分析如下: 由于工作需要我找了二个时间日期控制,这个不用js只要php实现的,因为要带参考查询操作,感兴趣的朋友可以参考一下...

PHP调用MsSQL Server 2012存储过程获取多结果集(包含output参数)的详解

【PHP Source Code】:复制代码 代码如下:$dbh = new PDO('sqlsrv:server=连接地址;Database=数据库名', 用户名, 密码);try {...