我从文件填充$ _SESSION ['products']数组:
$myFile = '.\products.txt';
$handle = fopen($myFile, 'r');
while (!feof($handle))
{
$prod = explode('|', fgets($handle));
$_SESSION['products'] = array($prod[4] => array(
'name' => $prod[0],
'price' => $prod[1],
'description' => $prod[2],
'image' => $prod[3]));
}
然后我想循环浏览它,打印所有名称和价格:
foreach ($_SESSION['products'] as $prodID=>$value) {
echo $_SESSION['products'][$value]['name'];
echo $_SESSION['products'][$value]['price'];
}
但它似乎不起作用!
答案 0 :(得分:4)
您需要再次检查foreach的工作原理。在您的情况下,您可以简单地执行以下操作:
foreach($_SESSION['products'] as $value) {
echo $value['name'];
echo $value['price'];
}
答案 1 :(得分:3)
你的问题是,在这里你用每个产品覆盖产品阵列,这意味着只有最后一个产品存在:
$_SESSION['products'] = array($prod[4] => array(
尝试附加到数组:
$_SESSION['products'][$prod[4]] = array(
// ^^^^^^^^ set the key as the product ID here
'name' => $prod[0],
'price' => $prod[1],
'description' => $prod[2],
'image' => $prod[3]);
你的foreach也错了,试试
foreach ($_SESSION['products'] as $prodID=>$value) {
echo $value['name'];
echo $value['price'];
}
答案 2 :(得分:0)
foreach ($_SESSION['products'] as $prodID=>$value) {
echo $_SESSION['products'][$prodID]['name'];
echo $_SESSION['products'][$prodID]['price'];
}