我有阵列:
print_r($_SESSION['cart']); echo '<br>';
print_r($_SESSION['itemamount']); echo '<br>';
print_r($_SESSION['itemproduct'])
分别带有值:
Array ( [sugar] => 989.32 [lolli] => 77 [isi] => 0.99 )
Array ( [0] => 13 [1] => 11 [2] => 2 )
Array ( [0] => 12861.16 [1] => 847 [2] => 1.98 )
我正在尝试同时对所有值进行foreach
循环,我能想到的只有:
foreach($_SESSION['cart'] as $data1 => $data2)
foreach($_SESSION['itemamount'] as $amount1=>$amount2)
foreach($_SESSION['itemproduct'] as $product1=>$product2)
{echo $data1 . ' x' . $amount2,
'<ul> price:', $product2 . '<br></ul>';}
它有效,但它复制了输出9次。请帮助。
sugar x2
price:1978.64
sugar x2
price:847
sugar x2
price:1.98
sugar x11
price:1978.64
sugar x11
price:847
sugar x11
price:1.98
sugar x2
price:1978.64
sugar x2
price:847
sugar x2
price:1.98
lolli x2
price:1978.64
lolli x2
price:847
lolli x2
price:1.98
lolli x11
price:1978.64
lolli x11
price:847
lolli x11
price:1.98
lolli x2
price:1978.64
lolli x2
price:847
lolli x2
price:1.98
isi x2
price:1978.64
isi x2
price:847
isi x2
price:1.98
isi x11
price:1978.64
isi x11
price:847
isi x11
price:1.98
isi x2
price:1978.64
isi x2
price:847
isi x2
price:1.98
答案 0 :(得分:0)
假设所有阵列的大小相同,请使用MultipleIterator
:
$i = new MultipleIterator;
$i->attachIterator(new ArrayIterator($cart));
$i->attachIterator(new ArrayIterator($amount));
$i->attachIterator(new ArrayIterator($product));
foreach ($i as $value) {
$keys = $i->key();
echo $keys[0]; // 'sugar'
echo $keys[1]; // 0
echo $keys[2]; // 0
echo $value[0]; // 989.32
echo $value[1]; // 13
echo $value[2]; // 12861.16
}
评论中只给出了第一次迭代的结果。
答案 1 :(得分:0)
我想以下内容应该会给你想要的结果。
$counter = 0;
foreach($_SESSION['cart'] as $data1 => $data2){
echo "{$data1} x {$_SESSION['itemamount'][$counter]}";
echo "<ul>price: {$_SESSION['itemproduct'][$counter]}</ul>";
$counter++;
}
如果没有,请告诉我。