在此循环中,我遍历数组并每次执行一次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 ]
);
使用另一个阵列,以保持结果:'$图[$ graphNum] = $ graph_results;' – axiac
你可以有一个数组?像'$ graphs = [];'在'foreach'之前,然后分配'$ graphs [$ graphNum] = $ graph_results;' – Giedrius
不使用数组的任何特定原因?如果你真的需要这些变量,你可能想看看这个http://php.net/manual/en/function.extract.php – Nima