2016-01-22 91 views
0

我有以下格式的數據數組,我發現它很難訪問元素,尤其是使用PHP的「數據」數組。從多維數組訪問元素與PHP

Array ( 
[jsonrpc] => 2.0 
[result] => Array ( 
    [random] => Array ( 
     [data] => Array ( 
      [0] => 15 
      [1] => 36 
      [2] => 11 
      [3] => 2 
      [4] => 31 
      [5] => 16 
      [6] => 19 
      [7] => 50 
      [8] => 24 
      [9] => 33 
      [10] => 3 
      [11] => 46 
      [12] => 37 
      [13] => 7 
      [14] => 29 
      [15] => 13 
      [16] => 52 
      [17] => 14 
      [18] => 49 
      [19] => 42 
      [20] => 40 
      [21] => 25 
      [22] => 39 
      [23] => 21 
      [24] => 28 
      [25] => 27 
      [26] => 34 
      [27] => 8 
      [28] => 10 
      [29] => 41 
      [30] => 45 
      [31] => 47 
      [32] => 26 
      [33] => 20 
      [34] => 12 
      [35] => 9 
      [36] => 6 
      [37] => 32 
      [38] => 18 
      [39] => 17 
      [40] => 38 
      [41] => 23 
      [42] => 5 
      [43] => 51 
      [44] => 35 
      [45] => 43 
      [46] => 44 
      [47] => 30 
      [48] => 48 
      [49] => 4 
      [50] => 1 
      [51] => 22 
         ) 
     [completionTime] => 2016-01-22 11:11:26Z 
        ) 
     [bitsUsed] => 296 
     [bitsLeft] => 933024 
     [requestsLeft] => 197725 
     [advisoryDelay] => 70 
       ) 
     [id] => 16083686) 

我已經試過

echo $myArray['data']; 

,但我得到了錯誤未定義指數:數據

我也試圖在foreach功能

foreach ($myArray as $row){ 
echo $row['result']['random']['data']; 
} 

,但我得到的錯誤非法字符串偏移'結果'

我已經有了我的時間,並很樂意獲得有關訪問此數組中的元素的幫助。

回答

1

必須指定的全路徑來訪問項目

echo $row['result']['random']['data'][0]; 

$行[「結果」] [「隨機」] [「數據」]是一個數組,並且函數回波不能顯示數組。要顯示數組,請使用print_r()或var_dump()。

var_dump($row['result']['random']['data']); 
print_r($row['result']['random']['data']); 

如果您要訪問的所有數據項,你可以使用:

foreach($row['result']['random']['data'] as $k => $v) { 
    echo $k . " = " . $v . "<br />"; 
} 
0

的元素存儲在這樣的事情,嘗試使用變量指數和循環播放,讓所有的值。

echo $row['result']['random']['data'][0]; 
echo $row['result']['random']['data'][1]; 
echo $row['result']['random']['data'][2];