php取出數組單個值

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,true),true);


項目中發現此問題 , 建議大家在php中將json和array轉換時 , json_encode() 和 json_decode()的第二個參數要加 true , 即:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章