php取出数组单个值的方法

栏目: 编程语言 · PHP · 发布时间: 6年前

内容简介:下面小编就为大家分享一篇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取出数组单个值的方法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Designing Programmes

Designing Programmes

Karl Gerstner / Springer Verlag / 2007 / $499.00

Karl Gerstnera (TM)s work is a milestone in the history of design. One of his most important works is Designing Programmes, which is presented here in a new edition of the original 1964 publication. I......一起来看看 《Designing Programmes》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具