【发布时间】:2017-08-29 16:21:13
【问题描述】:
在这个循环中,我正在遍历一个数组并每次都执行一个 API 调用。这很好用,但我一直在读到使用变量变量不是一个好习惯。我怎么能在不使用它们的情况下重写这段代码?
编辑:我没有使用数组,因为我必须将变量传递到另一个模板中,并且该数组之外还有其他变量。
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 ]
);
【问题讨论】:
-
使用另一个数组来保存结果:
$graph[$graphNum] = $graph_results; -
你可以有一个数组吗?
foreach之前的$graphs = [];之类的,然后分配$graphs[$graphNum] = $graph_results; -
不使用数组有什么特别的原因吗?如果你真的需要这些变量,你可能想看看这个php.net/manual/en/function.extract.php
-
我没有使用数组,因为我必须将变量传递给另一个也有其他变量的模板。
template( 'template-name', [ 'graphOne' => $graphOne, 'graphTwo' => $graphTwo, 'outsideVar' => $anothervalue ] );
标签: php loops variables foreach