PHP foreach在foreach循环中转向Twig

时间:2018-01-03 10:59:39

标签: php symfony foreach twig

我在PHP中使用以下代码进行foreach:

$fruit = array();

$fruit[] = array('id' => 1, 'name' => 'Banana 1');
$fruit[] = array('id' => 1, 'name' => 'Pear 1');
$fruit[] = array('id' => 1, 'name' => 'Mango 1');

$fruit[] = array('id' => 2, 'name' => 'Banana 2');
$fruit[] = array('id' => 2, 'name' => 'Pear 2');
$fruit[] = array('id' => 2, 'name' => 'Mango 2');

function get_pieces($id)
{
    $pieces = array();

    switch ($id)
    {
        case 1:
            $pieces[] = array('number' => 1);
            $pieces[] = array('number' => 2);
        break;

        case 2:
            $pieces[] = array('number' => 3);
            $pieces[] = array('number' => 4, 'qwerty' => 1);        
        break;
    }

    return $pieces;
}

foreach ($fruit as $item)
{
    echo '<p>';
    echo '<b>' . $item['name'] . '</b>';

    $pieces = get_pieces($item['id']);

    foreach ($pieces as $piece)
    {
        echo '<p>';
        echo '<i>' . $piece['number'] . '</i>';

        if (isset($piece['qwerty']))
        {
            echo ' => <i>qwerty is on</i>';
        }

        echo '</p>';
    }

    echo '</p>';
}

我想把它变成Twig模板。仅对于水果阵列,我没有问题,但是碎片部分,仅给出了Twig中的情况2的结果。在这里,您可以看到我使用的当前代码:

$render = array();

$render = array_merge($render, array('fruit' => $fruit));
$render = array_merge($render, array('pieces' => get_pieces(1)));

$render = array_merge($render, array('fruit' => $fruit));
$render = array_merge($render, array('pieces' => get_pieces(2)));

echo $twig->render('test.html', $render);

{% for f in fruit %}
    <p>{{ f.id }}</p>
    <p>{{ f.name }}</p>
    {% for p in pieces %}
        <p>Piece {{ p.number }}</p>
    {% endfor %}
{% endfor %}

有人可以帮助我,让这个第二件阵列在Twig工作也正确吗?

1 个答案:

答案 0 :(得分:1)

在合并array_merge_recursive数组时尝试使用pieces,因为array_merge将覆盖前一个数组中的键。

在两种情况下都使用相同的密钥,即01array_merge_recursive创建新的keys

https://3v4l.org/RBZDo

更新

将碎片连接到每块水果上,然后将其拉出阵列。

$fruit = array();

$fruit[] = array('id' => 1, 'name' => 'Banana 1', 'pieces' => get_pieces(1));
$fruit[] = array('id' => 1, 'name' => 'Pear 1', 'pieces' => get_pieces(1));
$fruit[] = array('id' => 1, 'name' => 'Mango 1', 'pieces' => get_pieces(1));

$fruit[] = array('id' => 2, 'name' => 'Banana 2', 'pieces' => get_pieces(2));
$fruit[] = array('id' => 2, 'name' => 'Pear 2', 'pieces' => get_pieces(2));
$fruit[] = array('id' => 2, 'name' => 'Mango 2', 'pieces' => get_pieces(2));

// ...

echo $twig->render('test.html', array('fruit' => $fruit));

{% for f in fruit %}
    <p>{{ f.id }}</p>
    <p>{{ f.name }}</p>
    {% for p in f.pieces %}
        <p>Piece {{ p.number }}</p>
    {% endfor %}
{% endfor %}

结果:

PHP:https://3v4l.org/kUKff
树枝:https://twigfiddle.com/p2hqsr