干涉PHP

时间:2016-10-31 09:42:04

标签: php loops variables

我正在尝试使用变量变量。在foreach循环中使用$type,我希望获得$week['one']$month['one']的值。

    $types = array(
        'week',
        'month'
    );

    $week = array(
        'one' => 1.2,
        'two' => 0.13,
    );

    $month = array(
        'one' => 1.2,
        'two' => 0.13,
    );

方法我尝试过没有成功:

    <?php foreach ($types as $type): ?>
            <?= $$type['one']; ?><br />
            <?= $$type['two']; ?><br />
    <?php endforeach; ?>

    <?php foreach ($types as $type): ?>
            <?= ${$type}['one']; ?><br />
            <?= ${$type}['two']; ?><br />
    <?php endforeach; ?>

    <?php foreach ($types as $type): ?>
            <?= $($type)['one']; ?><br />
            <?= $($type)['two']; ?><br />
    <?php endforeach; ?>

一切似乎都会导致语法错误。我使用了错误的语法吗?

1 个答案:

答案 0 :(得分:1)

使用此变体:

<?php foreach ($types as $type): ?>
        <?= ${$type}['one']; ?><br />
        <?= ${$type}['two']; ?><br />
<?php endforeach; ?>

在此处查看:https://3v4l.org/H7Pn7