在这个循环中,我每次都在迭代数组并执行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 ]
);
答案 0 :(得分:1)
如果您有多个具有不同key =&gt;值对的数组,则可以在进行array_merge
调用时使用PHP template()
。
如果您想要传递给模板的多个数组(key =&gt;值对),这是一个示例。
// 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));