我正在使用两个数组,$ local和$ national。目前,它们都在它们自己独立的foreach循环中,我正在使用如下:
$list // 1st array
$national // 2nd array
$numberlist = array();
$numbernational = array();
foreach($list as $rows)
{
// here I have a bunch of code that defines the variable $cheapestdeliverydate
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $rows;
}
}
foreach($national as $rows)
{
// here I have a bunch of code that defines the variable $cheapestdeliverydate
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numbernational[] = $rows;
}
}
有没有办法合并这两个foreach函数?我尝试了以下内容:
foreach(array_merge($list, $national) as $rows)
{
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $rows;
$numbernational[] = $rows;
}
}
但不幸的是,当我在$ numberlist和$ numbernational上进行print_r
时,他们都返回完全相同的数组。事后来看,这对我来说很有意义,所以我想知道我是否可以按照以下方式做点什么:
foreach($list as $row, $national as $rows)
{
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $row;
$numbernational[] = $rows;
}
}
$ list和$ national数组的大小相同。
答案 0 :(得分:1)
您可以使用SPL的MultipleIterator
一次遍历两个数组$numberlist = [];
$numbernational = [];
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($list));
$mi->attachIterator(new ArrayIterator($national));
$result = array();
foreach($mi as list($listRow, $nationalRow)) {
if (strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate)) {
$numberlist[] = $listRow;
$numbernational[] = $nationalRow;
}
}
答案 1 :(得分:0)
由于您的代码逻辑,它必须只是
$list // 1st array
$national // 2nd array
$numberlist = array();
$numbernational = array();
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate)
{
$numberlist = $list;
$numbernational = $national;
}
答案 2 :(得分:-3)
尝试类似:
$all = array_merge($list, $national);
foreach($all as $rows)
{
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $rows;
$numbernational[] = $rows;
}
}