2017-08-29 118 views
0

在此循环中,我遍历数组并每次执行一次API调用。这工作正常,但我一直在阅读,使用变量变量是不好的做法。我如何重写这段代码而不使用它们?在PHP中替代变量变量

编辑:我没有使用数组,因为我必须将变量传递到另一个模板中,并在该数组之外具有其他变量。

template('template-name', [ 'graphOne' => $graphOne, 'graphTwo' => $graphTwo, 'outsideVar' => $anothervalue ]);

<?php 

// Array of categories for each graph 
$catArray = [ 
    'One' => '3791741', 
    'Two' => '3791748', 
    'Three' => '3791742', 
    'Four' => '3791748' 
]; 

foreach ($catArray as $graphNum => $cat) 
{ 
     // Hit API 
     $graph_results = theme('bwatch_graph_call', [ 
       'project' => '153821205', 
       'category' => $cat 
      ] 
     ); 

     ${"graph{$graphNum}"} = $graph_results; 
     // Outputs $graphOne, $graphTwo, $graphThree... 

} 

// Pass vars to template 
template('template-name', [ 
'graphOne' => $graphOne, 
'graphTwo' => $graphTwo, 
'outsideVar' => $anothervalue ] 
); 
+4

使用另一个阵列,以保持结果:'$图[$ graphNum] = $ graph_results;' – axiac

+2

你可以有一个数组?像'$ graphs = [];'在'foreach'之前,然后分配'$ graphs [$ graphNum] = $ graph_results;' – Giedrius

+0

不使用数组的任何特定原因?如果你真的需要这些变量,你可能想看看这个http://php.net/manual/en/function.extract.php – Nima

回答

1

您可以使用PHP的array_merge当你让你的template()电话,如果你有不同的密钥多个阵列=>值对。

http://php.net/array_merge

下面是一个例子,如果你有多个阵列(密钥=>值对)要传递到模板中。

// Array of categories for each graph 
$catArray = [ 
    'One' => '3791741', 
    'Two' => '3791748', 
    'Three' => '3791742', 
    'Four' => '3791748' 
]; 

// Array of category results 
$catResult = []; 

foreach ($catArray as $graphNum => $cat) 
{ 
     // Hit API 
     $catResult['graph' . $graphNum] = theme('bwatch_graph_call', [ 
       'project' => '153821205', 
       'category' => $cat 
      ] 
     ); 
} 

// Now you have an array of results like... 
// $catResult['graphOne'] = 'result for One'; 
// $catResult['graphTwo'] = 'result for Two'; 

$otherArray1 = ['outsideVar' => $anothervalue]; 

$otherArray2 = ['somethingElse' => $oneMoreValue]; 

// Pass all arrays as one 
template('template-name', array_merge($catResult, $otherArray1, $otherArray2)); 
+0

非常感谢,很有道理。 – user3869231