繁体   English   中英

在关联数组中推送数组键和值

[英]push array key and value in associative array

我想将数组推入现有的会话数组。 我想使用get [id]并且我希望能够堆叠所有添加的数组,而不是在推送新数组时删除它们。

波纹管是我的代码,我没有得到值,而是得到了这个错误---数组到字符串的转换。 提前致谢。

**CODE
  <?php
session_start();

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

}


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

 foreach($_SESSION['animals'] as $key=>$value)
 {   

    // and print out the values

    echo $key; 
    echo $value;
    }
?>

对于您的代码,这是$ _SESSION的样子:

array (size=1)
  'animals' => 
    array (size=1)
      0 => 
        array (size=1)
          'id' => string 'test' (length=4)

在您的代码中:

foreach($_SESSION['animals'] as $key=>$value)

key将包含0value将包含array('id' => 'test') 由于value是一个数组,因此无法像这样回显它。

如果您想回显每种动物的所有特征,此代码将起作用:

<?php
session_start();

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

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

// We go through each animal
foreach($_SESSION['animals'] as $key=>$animal)
{   
    echo 'Animal n°'.$key; 
    // Inside each animal, go through each attibute
    foreach ($animal as $attribute => $value)
    {
        echo $attribute;
        echo $value;

    }
}

暂无
暂无

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

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