在php中循环遍历此数组的最佳方法

时间:2011-04-05 05:59:11

标签: php arrays loops

当我使用print_r()时,我有一个api调用比特币返回这个aray,循环它的最佳方式是什么,以便我可以使用数据生成表格或图表?

[{"volume": 1E+1, "timestamp": 1301982430, "symbol": "mtgoxUSD", "price": 0.62}, 
{"volume": 1E+1, "timestamp": 1301982430, "symbol": "mtgoxUSD", "price": 0.62}, 
{"volume": 31, "timestamp": 1301981474, "symbol": "mtgoxUSD", "price": 0.64}, 
{"volume": 8.592, "timestamp": 1301981466, "symbol": "mtgoxUSD", "price": 0.6401}, 
{"volume": 10.89, "timestamp": 1301981466, "symbol": "mtgoxUSD", "price": 0.6401}, 
{"volume": 9.61, "timestamp": 1301981066, "symbol": "mtgoxUSD", "price": 0.641},
{"volume": 1E+1, "timestamp": 1301981058, "symbol": "mtgoxUSD", "price": 0.641}, 
{"volume": 21.654, "timestamp": 1301981058, "symbol": "mtgoxUSD", "price": 0.641},
{"volume": 2E+1, "timestamp": 1301980388, "symbol": "mtgoxUSD", "price": 0.6729}, 
{"volume": 1E+1, "timestamp": 1301980373, "symbol": "mtgoxUSD", "price": 0.641}]

3 个答案:

答案 0 :(得分:5)

您可以先使用JSON将此json_decode()字符串转换为PHP数组:

$str = '[{"volume": 1E+1, "timestamp": 1301982430, "symbol": "mtgoxUSD", "price": 0.62}, {"volume": 1E+1, "timestamp": 1301982430, "symbol": "mtgoxUSD", "price": 0.62}, {"volume": 31, "timestamp": 1301981474, "symbol": "mtgoxUSD", "price": 0.64}, {"volume": 8.592, "timestamp": 1301981466, "symbol": "mtgoxUSD", "price": 0.6401}, {"volume": 10.89, "timestamp": 1301981466, "symbol": "mtgoxUSD", "price": 0.6401}, {"volume": 9.61, "timestamp": 1301981066, "symbol": "mtgoxUSD", "price": 0.641}, {"volume": 1E+1, "timestamp": 1301981058, "symbol": "mtgoxUSD", "price": 0.641}, {"volume": 21.654, "timestamp": 1301981058, "symbol": "mtgoxUSD", "price": 0.641}, {"volume": 2E+1, "timestamp": 1301980388, "symbol": "mtgoxUSD", "price": 0.6729}, {"volume": 1E+1, "timestamp": 1301980373, "symbol": "mtgoxUSD", "price": 0.641}]';
$data = json_decode($str);


然后,迭代这些数据的最简单方法是使用foreach循环:

foreach ($data as $item) {
    echo "{$item->volume} - {$item->timestamp} - {$item->symbol} - {$item->price} <br />";
}


哪个可以得到这样的东西:

10 - 1301982430 - mtgoxUSD - 0.62
10 - 1301982430 - mtgoxUSD - 0.62
31 - 1301981474 - mtgoxUSD - 0.64
8.592 - 1301981466 - mtgoxUSD - 0.6401
10.89 - 1301981466 - mtgoxUSD - 0.6401
9.61 - 1301981066 - mtgoxUSD - 0.641
10 - 1301981058 - mtgoxUSD - 0.641
21.654 - 1301981058 - mtgoxUSD - 0.641
20 - 1301980388 - mtgoxUSD - 0.6729
10 - 1301980373 - mtgoxUSD - 0.641 

答案 1 :(得分:1)

数组看起来像json编码,你必须用json_decode

解码它
$array=json_decode($array,true);

并使用foreach循环迭代数组

foreach($array as $key => $value)
{
  echo $key." has the value ".$value;
}

答案 2 :(得分:1)

将其解码为普通数组:

$str = json_decode($string);