如何同时(并行)遍历多个数组


How to loop through multiple arrays at the same time (parallel)

Oke 所以我不知道为什么这这么难,我找到的所有信息都只针对像array_combine这样的两个数组。

我有 3 个数组,我从表单中动态创建的输入字段中获取,所以现在我想检索数据并将其打印出来,如下所示:

Item1 (array1)
Item1 (array2)
Item1 (array3)
Item2 (array1)
Item2 (array2)
Item2 (array3)

但是现在使用我的代码,它完成了一个数组,然后转到下一个数组。

$article_id = $_REQUEST['article_id'];
$article_descr = $_REQUEST['article_descr'];
$article_ammount = $_REQUEST['article_amount'];
foreach($article_id as $artid) {
    echo = 'Article id: '.$artid.'<br>';
}
foreach($article_descr as $art_descr) {
    echo 'Article description: '.$art_descr.'<br>';
}
foreach($article_ammount as $art_amount) {
    echo 'Article ammount: '.$art_amount.'<br>';
}

既然你说所有数组都通过它们的键匹配,我假设你有这样的东西:

$article_ids = [10, 22, 13];
$article_descriptions = ["this is one", "this is two", "this is three"];
$article_amounts = [20, 10, 40];

因此,为了有序地获取他们的信息,您首先需要找到有多少元素。我们可以使用第一个数组的总和,通过使用 count() ,然后使用 for 循环来迭代并获取每个数组的信息。

//get the number of articles
$num = count($article_ids);
//iterate through each article count
for ($i = 0; $i < $num; $i++){
    echo 'Article id: '.$article_ids[$i].'<br>';
    echo 'Article description: '.$article_descriptions[$i].'<br>';
    echo 'Article amount: '.$article_amounts[$i] .'<br>';
}

如果您确定每个项目的信息在所有数组中都位于同一个键下,则可以执行以下操作:

$article_id = $_REQUEST['article_id'];
$article_descr = $_REQUEST['article_descr'];
$article_ammount = $_REQUEST['article_amount'];
foreach ($article_id as $id => $value) {
    echo 'Article id: ' . $value . '<br>';
    echo 'Article description: ' . $article_descr[$id] . '<br>';
    echo 'Article ammount: ' . $article_ammount[$id] . '<br>';
}