当前位置:Gxlcms > PHP教程 > php取出数组单个值方法解析

php取出数组单个值方法解析

时间:2021-07-01 10:21:17 帮助过:5人阅读

这次给大家带来php取出数组单个值方法解析,php取出数组单个值的注意事项有哪些,下面就是实战案例,一起来看一下。

1.数组arr

var_dump(arr) 值如下:

  1. array (size=3)
  2. 'delete' =>
  3. array (size=3)
  4. 0 => string 'HBSFlyRecode20170222-101501.txt' (length=31)
  5. 1 => string 'HBSFlyRecode20170222-105502.txt' (length=31)
  6. 2 => string 'HBSFlyRecode20170222-108803.txt' (length=31)
  7. 'new' =>
  8. array (size=3)
  9. 0 => string 'HBSFlyRecode20170223-101504.txt' (length=31)
  10. 1 => string 'HBSFlyRecode20170223-105505.txt' (length=31)
  11. 2 => string 'HBSFlyRecode20170223-108806.txt' (length=31)
  12. 'old' =>
  13. array (size=3)
  14. 0 => string 'HBSFlyRecode20170221-101507.txt' (length=31)
  15. 1 => string 'HBSFlyRecode20170221-105508.txt' (length=31)
  16. 2 => string 'HBSFlyRecode20170221-108809.txt' (length=31)
  1. echo $arr['old'][0];
  2. 打印出: HBSFlyRecode20170221-101507.txt

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

  1. var_dump(arr)
  2. object(stdClass)[1]
  3. public 'delete' =>
  4. array (size=3)
  5. 0 => string 'HBSFlyRecode20170222-101501.txt' (length=31)
  6. 1 => string 'HBSFlyRecode20170222-105502.txt' (length=31)
  7. 2 => string 'HBSFlyRecode20170222-108803.txt' (length=31)
  8. public 'new' =>
  9. array (size=3)
  10. 0 => string 'HBSFlyRecode20170223-101504.txt' (length=31)
  11. 1 => string 'HBSFlyRecode20170223-105505.txt' (length=31)
  12. 2 => string 'HBSFlyRecode20170223-108806.txt' (length=31)
  13. public 'old' =>
  14. array (size=3)
  15. 0 => string 'HBSFlyRecode20170221-101507.txt' (length=31)
  16. 1 => string 'HBSFlyRecode20170221-105508.txt' (length=31)
  17. 2 => string 'HBSFlyRecode20170221-108809.txt' (length=31)

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

  1. function getValue($arr){
  2. foreach($arr as $key => $value){
  3. if(is_array($value)){
  4. getValue($value);
  5. }else{
  6. echo $value."<br>";
  7. }
  8. }
  9. }

如果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)得到的是数组

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

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

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

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

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

PHP实现路由与类自动加载步骤详解

php操作字符串分割成数组

以上就是php取出数组单个值方法解析的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行