简体   繁体   English

连续输出来自不同数组的几个值

[英]output several values from different arrays consecutively

I have arrays: 我有数组:

print_r($_SESSION['cart']); echo '<br>';
print_r($_SESSION['itemamount']); echo '<br>';
print_r($_SESSION['itemproduct'])

with values respectively: 分别具有以下值:

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 )

I am trying to do a foreach loop for all their values at the same time and all I could think of was: 我试图同时为它们的所有值做一个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>';}

it worked but it replicated the output 9 times. 它可以工作,但是将输出复制了9次。 Help please. 请帮助。

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

Assuming all arrays have the same size, use MultipleIterator : 假设所有数组的大小相同,请使用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
}

Only the results of the first iteration are given in the comments. 注释中仅给出第一次迭代的结果。

I guess the following should give you the desired result. 我想以下应该会给您想要的结果。

$counter = 0;
foreach($_SESSION['cart'] as $data1 => $data2){
   echo "{$data1} x {$_SESSION['itemamount'][$counter]}";
   echo "<ul>price: {$_SESSION['itemproduct'][$counter]}</ul>";
   $counter++;
}

Let me know if it doesn't. 让我知道是否可以。

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

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