【问题标题】:Alternative to Variable Variables in PHPPHP 中可变变量的替代方案
【发布时间】: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' =&gt; $graphOne, 'graphTwo' =&gt; $graphTwo, 'outsideVar' =&gt; $anothervalue ] );

标签: php loops variables foreach


【解决方案1】:

如果您有多个具有不同键=>值对的数组,则可以在调用 template() 时使用 PHP 的 array_merge

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));

【讨论】:

    猜你喜欢
    • 2011-04-27
    • 2017-05-13
    • 2018-01-15
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多