如何同时遍历多个数组(并行) [英] How to loop through multiple arrays at the same time (parallel)

查看:120
本文介绍了如何同时遍历多个数组(并行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我不知道为什么这么难,我发现的所有信息仅适用于两个数组,例如array_combine.

Oke so I don't know why this is so hard, all information I find is only for two arrays like array_combine.

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

I have 3 arrays that I get from dynamically created input fields in a form, so now I want to retrieve the data and print it out like:

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

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

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

But with my code right now it completes one array and than goes to the next.

$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>';
}

推荐答案

由于您说过所有数组都按其键匹配,所以我假设您有这样的东西:

Since you said that all arrays match by their keys, I will assume you have something like this:

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

因此,为了有条不紊地获取其信息,您首先需要找到有多少个元素.我们可以使用第一个数组的总数,方法是使用 count(),然后使用 for 循环来迭代并获取每个数组的信息.

Therefore in order to obtain their information in an orderly manner, you would first need to found how many elements there are. We can use the total of the first array, by using count(), then using a for loop to iterate and obtain each array's information.

//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>';
}

这篇关于如何同时遍历多个数组(并行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆