主頁 > 知識庫 > php取出數(shù)組單個值的方法

php取出數(shù)組單個值的方法

熱門標簽:阿里云 Linux服務器 Mysql連接數(shù)設置 科大訊飛語音識別系統(tǒng) 銀行業(yè)務 服務器配置 電子圍欄 團購網(wǎng)站

1.數(shù)組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是對象形式 , 打印結(jié)果如下:

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對象和數(shù)組通用的foreach方式取值:

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

如果arr為對象形式 , 可以考錄將對象轉(zhuǎn)為數(shù)組形式 , 這里提供一種快捷方式:

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

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

2. json_decode($object_json) 和 json_decode($json)得到的是數(shù)組對象

json_decode($object_json,true) 和 json_decode($json,true)得到的是數(shù)組

綜上 , 可以將數(shù)組對象轉(zhuǎn)為數(shù)組的方式:

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

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

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

以上這篇php取出數(shù)組單個值的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • PHP獲取數(shù)組中單列值的方法
  • PHP獲取數(shù)組最后一個值的2種方法
  • php在數(shù)組中查找指定值的方法

標簽:大理 廣元 蚌埠 衢州 萍鄉(xiāng) 衡水 江蘇 棗莊

巨人網(wǎng)絡通訊聲明:本文標題《php取出數(shù)組單個值的方法》,本文關鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權(quán)與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266