PHP如何从数组中获取特定值并将其存储在$ _SESSION中

时间:2018-09-30 22:37:18

标签: php arrays session

我有一个要在其中获取特定值(“创建”)的数组,然后将$_SESSION存储在新数组中。我该如何实现?

我的数组看起来像这样

Array
    (
        [0] => Array
            (
                [product_id] => 679
                [quantity] => 1
                [created] => 2018-10-01
            )

        [1] => Array
            (
                [product_id] => 677
                [quantity] => 1
                [created] => 2018-10-05
            )

        [2] => Array
            (
                [product_id] => 678
                [quantity] => 1
                [created] => 2018-10-03
            )

    )

我尝试过类似的事情:

foreach($created as $i) {
   $values = [$i]['created'];
   echo $values;
}

session_start();
$_SESSION['creation_dates'] = $values;

但这不起作用。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

您需要先开始会话,然后再进行任何输出。您的echo阻止了这种情况。您必须获得Notices,但看不到它们,具体取决于您的error_reporting

请尝试以下代码:

session_start();

$values = array();
foreach($creation_dates as $i) {
   $values[] = $i['created'];
}

$_SESSION['creation_dates'] = $values;

print_r($values);
print_r($_SESSION['creation_dates']);