简体   繁体   English

多维会话php数组回显

[英]Multidimensional session php array echoing

I have a PHP session array where it can be counted as multidimensional array, basically I am trying to store data inside my session array and i am successfully obtaining that part of the task. 我有一个PHP会话数组,在这里它可以算作多维数组,基本上,我正在尝试将数据存储在会话数组中,并且我成功地完成了任务的那一部分。 The main issue is, I am not able to echo them specifically and I have to use var_dump. 主要问题是,我无法明确地回显它们,因此必须使用var_dump。 When I try to print them with echo i got an notice which says array to string conversion. 当我尝试用echo打印它们时,我收到一条通知,说从数组到字符串转换。 Please any help I would be appreciated how to print them with their own specific keys or values. 请任何帮助,我将不胜感激如何使用它们自己的特定键或值打印它们。 The code as follows: 代码如下:

if (!is_array($_SESSION['products']['names'])){

  $_SESSION['products']['names'] = array();
  $_SESSION['products']['names']['prices']= array();

  }else {

    $pros = $_SESSION['products']['names'];

    if (in_array($product->getName(), $pros, true)){

    echo 'The product is available in your basket';

  } else {

    array_push($_SESSION['products']['names'],$product->getName());
    array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));


    foreach ($_SESSION['products']  as  $val){

      echo $val['names'];
      echo $val['prices'];

    }
  }

}

The output that I receive as follows: 我收到的输出如下:

Notice: Undefined index: names in 注意:未定义索引:中的名称

Array to string conversion in 数组到字符串的转换

Use join() function in your foreach, like this: 在foreach中使用join()函数,如下所示:

echo join('<br>', $val);

Or instead of 或者代替

echo $val['prices'];

write

echo $val['names']['prices'];

This is your problem... 这是你的问题...

// Here your assigning `['names']` as a string..
array_push($_SESSION['products']['names'],$product->getName());

// Then here you're overwriting the string with an array...
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));

Change the first one to this.. 将第一个更改为此。

array_push($_SESSION['products']['names']['name'],$product->getName());

Assuming $product->getPrice() returns a string or a number... 假设$product->getPrice()返回一个字符串或一个数字...

foreach ($_SESSION['products']  as  $val){
    foreach($val['names'] as $name){
        echo $name['name'];
        echo $name['prices'];
    }
}

There is no issue with the code you have here. 您在这里的代码没有问题。 I don't see you trying to echo or vardump them directly so please show the code you are echoing them out specifically or the output from above and which line is giving you an issue. 我看不到您试图直接回显或暗示它们的原因,因此请显示您正在回显它们的代码或上面的输出以及哪一行给您带来了问题。

If you want to echo each one out with it's price. 如果您想用价格来回声每个人。

for($i=0;$i<count($_SESSION['products']['names']);$i++) {
echo $_SESSION['products']['names'][$i] . " " . $_SESSION['products']['names']['price'][$i];
}

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

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