我正在尝试循环访问某些CSV数据并取出$ data [4]项。我最终的目标是找到平均值,并希望使用PHP的array_sum。这似乎是有效的,除了每次我尝试创建这个数组时,我的while循环将每个值分成它们各自独立的数组($ real),而不是我可以使用的一个数组。我已经尝试了所有的东西,包括在循环之外使用数组,但没有任何工作。任何帮助将不胜感激!
$symbol=array("XOM","CVX","RDS-A",
"PTR","TOT","SNP","COP",
"IMO","BP","E","STO","EC","SU","MRO");
for($i=0; $i<count($symbol);$i++)
{
$handle = @fopen("http://ichart.yahoo.com/table.csv?s={$symbol[$i]}&a=10&b=12&c=2013&d=10&e=12&f=2013&g=d&ignore=.csv", "r", false, $context);
if ($handle === false)
{
// trigger (big, orange) error
trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
exit;
}
// download title of CSV file and throw away
$data=fgetcsv($handle);
//loop through data
while(($data = fgetcsv($handle)) !==FALSE)
{
$rows++;
$num=count($data);
$real=array($data[4]);
}
var_dump($real);
}
这是我的最终结果:
array(1) { [0]=> string(9) "92.669998" }
array(1) { [0]=> string(6) "120.00" }
array(1) { [0]=> string(9) "66.290001" }
array(1) { [0]=> string(10) "111.059998" }
array(1) { [0]=> string(5) "58.73" }
array(1) { [0]=> string(9) "82.449997" }
array(1) { [0]=> string(5) "72.82" }
array(1) { [0]=> string(9) "42.740002" }
array(1) { [0]=> string(5) "45.91" }
array(1) { [0]=> string(5) "47.98" }
array(1) { [0]=> string(9) "22.440001" }
array(1) { [0]=> string(5) "41.93" }
array(1) { [0]=> string(5) "34.82" }
array(1) { [0]=> string(5) "35.82" }
答案 0 :(得分:0)
不确定$context
是什么,但试试这个......
$symbol=array("XOM","CVX","RDS-A","PTR","TOT","SNP","COP","IMO","BP","E","STO","EC","SU","MRO");
$datas = array();
for($i=0; $i<count($symbol);$i++){
$handle = @fopen("http://ichart.yahoo.com/table.csv?s={$symbol[$i]}&a=10&b=12&c=2013&d=10&e=12&f=2013&g=d&ignore=.csv", "r", false, $context);
if ($handle === false){
// trigger (big, orange) error
trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
exit;
}
// download title of CSV file and throw away
$data=fgetcsv($handle);
//loop through data
while(($data = fgetcsv($handle)) !==FALSE){
$rows++;
$datas[] = $data[4];
}
}
print_r($datas);