【问题标题】:cant push array key and value无法推送数组键和值
【发布时间】:2015-11-17 15:06:01
【问题描述】:

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

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

第 10 行

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

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

提前致谢,下面是我的完整代码!

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/>";
}
?>

【问题讨论】:

    标签: php arrays session


    【解决方案1】:

    你应该试试:

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

    merging

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

    union

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

    【讨论】:

    • 我忘了建立一个联合......所以现在它也被添加了!
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2021-01-25
    • 2019-07-02
    • 2022-08-18
    • 2022-12-12
    • 2018-09-04
    相关资源
    最近更新 更多