2013-03-07 135 views
0

我知道我的问题的标题可能令人困惑,但我不太清楚如何解释我想要做的简洁。在foreach循环中声明不同的变量

我想通过一个CSV数组循环,并将数据加载到具有不同名称的变量中。在下面的示例中,不是$foo_data而是通过$stocks阵列的每个循环中的$MSFT_data,$AAPL_data$FB_data

$stocks = array($msft, $aapl, $fb); 

foreach ($stocks as $stock) { 
    $fh = fopen($stock, 'r'); 
    $header = fgetcsv($fh); 

    $foo_data = array(); 
    while ($line = fgetcsv($fh)) { 
     $foo_data[] = array_combine($header, $line); 
    } 

    fclose($fh); 
} 

如果您需要更多信息,请让我知道。

+1

什么错误?问题是什么? – 2013-03-07 07:53:18

+0

为什么不使用2D阵列? '$ stock_data [$ stock] [] = array_combine($ header,$ line);' – Johnsyweb 2013-03-07 07:53:21

+0

我尝试在每个循环中通过foreach在我的示例中将数据保存到不同名称的变量。 – 585connor 2013-03-07 07:55:00

回答

2

有两个问题。首先是你不能得到变量名,所以脚本无法知道有一个$msft,$aapl,$fb,所以你需要传递名称与数组一起。第二个是你需要变量变量。

尝试

$stocks = array('MSFT' => $msft, 'AAPL' => $aapl, 'FB' => $fb); 
foreach ($stocks as $key=>$stock) { 
    $fh = fopen($stock, 'r'); 
    $header = fgetcsv($fh); 

    $varname = $key . '_data'; 

    $$varname = array(); //the double $$ will set the var content as variable ($MSFT_data) 
    while ($line = fgetcsv($fh)) { 
     ${$varname}[] = array_combine($header, $line); 

     //the {} are needed to let PHP know that $varname is the name of the variable and not $varname[]. 
    } 

    fclose($fh); 
} 
+0

我得到错误“致命错误:不能使用[]读取''$$ varname [] = array_combine($ header,$ line)';' – 585connor 2013-03-07 08:13:53

+0

我忘记在$ varname周围添加'{}'。 – 2013-03-07 08:36:57

0
$MSFT_data = $foo_data[0]; 
$AAPL_data = $foo_data[1]; 
$FB_data = $foo_data[2]; 

这对您有什么用?