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=jsondecode(jsonencode(arr,true),true);
json_encode(arr,true);jsondecode(arr,true);jsondecode(json,true);
以上是php如何取出數組單一值的詳細內容。更多資訊請關注PHP中文網其他相關文章!