I use the following code for foreach in PHP:
$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>';
}
I want to get this into a Twig template. For the fruit array only, I have no problems, but the pieces part, gives only the results of case 2 in Twig. Here you see the current code I use:
$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 %}
Can someone help me, to get this second pieces array also correct working in Twig?