繁体   English   中英

无法推送数组键和值

[英]cant push array key and value

我有一个名为animal.php的页面,该页面具有一个动物名称列表,每个动物名称旁边都有一个按钮。 单击任何按钮时,会将用户发送到showanimal.php,其中动物名称显示为$ value,并且$ key自动递增。 我正在使用foreach循环显示它,以便可以显示单击的每只动物的所有动物的名称。

问题是,我在get [id]旁边的array_push中添加了“ size =>”,以便可以设置自己的密钥,而不是自动递增的密钥。 但是我收到一个错误消息,说“”。 语法错误,第10行(此行下方)出现意外的'=>'(T_DOUBLE_ARROW)。

10号线

array_push($_SESSION['animals'],    "size" => "".$_GET['id']."" );

我必须设置一个不会自动递增的键,因为稍后需要更新每个键。 我如何解决这个令人沮丧的问题,因为它在没有push数组的情况下可以工作...

在此先感谢,下面是我的完整代码!

animal.php

    <div class="product">
    <h3>BIRD</h3>
    <a href="showanimal.php?id=bird">Add animal</a>
</div>

<div class="product">
    <h3>DOG</h3>
<a href="showanimal.php?id=dog">Add animal</a>
</div>

<div class="product">
    <h3>LION</h3>
    <a href="showanimal.php?id=lion">Add animal</a>
</div>

showanimal.php

    <?php
session_start();

if(empty($_SESSION['animals']))
{
$_SESSION['animals'] = array();
}

// push array using get id as KEY and size as VALUE.
    // getting error on the line bellow " unexpected '=>' (T_DOUBLE_ARROW)"
array_push($_SESSION['animals'],    "size" => "".$_GET['id']."" );

// We go through each animal
foreach($_SESSION['animals'] as $key=>$value)
{   
echo "the key is :::::::: " . $key;
echo "<BR/>";
echo "the value is :::::::: " . $value;
echo "<BR/>";
echo "---------------------------------";
echo "<BR/>";
}
?>

你应该试试:

$_SESSION['animals']['size'] = $_GET['id'];

合并

$_SESSION['animals'] = array_merge( $_SESSION['animals'], 
    array( 'size' => $_GET['id'] ) );

工会

$_SESSION['animals'] += array( 'size' => $_GET['id'] );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM