我正在使用Symfony2,版本2.7。但任何人都应该能够回答这个问题,因为它与symfony不完全相关。如何阻止数组被覆盖?
我有一个功能。我想要该函数添加一个新的项目(一旦从表单中点击)到一个数组。相反,我的数组不断被被点击的新项目覆盖。
我尝试了一些foreach循环,但不能正确的。请,任何帮助表示赞赏。
以下是相关功能。
/**
* Displays Bought Items
*
* @Route("/buy/{id}", name="item_buy")
* @Method("GET")
* @Template()
*/
public function buyAction(Request $request, $id)
{
$session = $request->getSession();
$cart[] = $id;
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:Item')->find($id);
$entities = $em->getRepository('AppBundle:Item')->findAll();
$session->set('cart', $cart);
if (!$entity) {
throw $this->createNotFoundException('No Item ');
} else {
$cart[$entity->getId()] = $entity->getName();
}
$session->set('cart', $cart);
return array(
'cart' => $cart,
'entity' => $entity,
'entities' => $entities,
);
}
它是如何在树枝被使用:
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Items Bought...</h1>
<table class="record_properties">
<h3>You Bought...</h3>
{# {% if entity is defined %} #}
{% for key, cartValue in cart %}
<tr>
<td>{{ key }}: {{ cartValue }}</td>
{{ dump(entity.name) }}
{{ dump(cart) }}
</tr>
{% endfor %}
{# {% endif %} #}
<tbody>
{% for entity in entities %}
<tr>
<td><a href="{{ path('item_show', { 'id': entity.id }) }}">{{ entity.id }}</a></td>
<td>{{ entity.name }}</td>
<td>
<ul>
<li>
<a href="{{ path('item_buy', { 'id': entity.id }) }}">Buy</a>
</li>
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<ul class="record_actions">
<li>
<a href="{{ path('item') }}">
Back to the list
</a>
</li>
{% endblock %}
btw是什么原因在这里添加'$ id'到数组'$ cart [] = $ id;'? 这条线 '$ cart [$ entity-> getId()] = $ entity-> getName();' 应该就够了。 – LuckyLue
这只是为了演示分配给哪个id,以及我将在哪里放置代码片段? –
尝试替换'$ cart [] = $ id;'=>'$ cart = $ this-> get('session') - > get('cart',[]);' – LuckyLue