如何解决PHP嵌套的foreach循环中的重置变量

时间:2019-04-21 05:46:37

标签: php loops foreach

我有一个已转换为数组的字符串,但想在列表中显示它们。如何重置循环以避免重复?

我尝试将变量设置为空白,通常用于单个foreach语句

$SEAT = "1A,4A";
$NAME = "John Doe, Jane Doe";
$PHONE_NUMBER = "123456856,1235668";


$SEAT_USSD_STRING_VALUE = explode(",", $SEAT);
$NAME_USSD_STRING_VALUE = explode(",", $NAME);
$PHONE_USSD_STRING_VALUE = explode(",", $PHONE_NUMBER);

$seat_value = "";
foreach ($SEAT_USSD_STRING_VALUE as $seat_key => $seat_value) {
    $name_value = "";
    foreach ($NAME_USSD_STRING_VALUE as $name_key => $name_value) {
        $phone_number_value = "";
        foreach ($PHONE_USSD_STRING_VALUE as $phone_number_key => $phone_number_value) {
            echo "$seat_value: $name_value - $phone_number_value<br/>";
        }
    }
}

我希望得到

1A: John Doe - 12345678
4A: Jane Doe - 87654321

但是我得到了

1A: John Doe - 12345678
1A: John Doe - 87654321
1A: Jane Doe - 12345678
1A: Jane Doe - 87654321
4A: John Doe - 12345678
4A: John Doe - 87654321
4A: Jane Doe - 12345678
4A: Jane Doe - 87654321

3 个答案:

答案 0 :(得分:3)

您可以这样做,假设您在3个数组中的元素数量始终相等:

<?php

$SEAT = "1A,4A";
$NAME = "John Doe, Jane Doe";
$PHONE_NUMBER = "123456856,1235668";

$SEAT_USSD_STRING_VALUE = explode(",", $SEAT);
$NAME_USSD_STRING_VALUE = explode(",", $NAME);
$PHONE_USSD_STRING_VALUE = explode(",", $PHONE_NUMBER);

$seat_value = "";
foreach ($SEAT_USSD_STRING_VALUE as $seat_index => $seat_value) {
    $name_value = $NAME_USSD_STRING_VALUE[$seat_index];
    $phone_value = $PHONE_USSD_STRING_VALUE[$seat_index];
    echo "$seat_value: $name_value - $phone_value<br/>";
}

在这种情况下,您始终可以引用其他数组中位于相同索引上的项目。

这将在以下情况下起作用:我们在座位阵列循环中的索引为0处,然后名称将为名称阵列的0索引元素,而电话将为电话阵列的0索引元素。 / p>

答案 1 :(得分:0)

您只需要使用在您的第一个$seat_key中可以访问的密钥(foreach

使用此foreach代替所有人foreach

foreach ($SEAT_USSD_STRING_VALUE as $seat_key => $seat_value) {
        echo "$seat_value: $NAME_USSD_STRING_VALUE[$seat_key] - $PHONE_USSD_STRING_VALUE[$seat_key]<br/>";
}

答案 2 :(得分:0)

您可以使用array_mergeexplodearray_walk获得所需的结果

$arr = array_merge(
    explode(',',$SEAT),
    explode(',',$NAME),
    explode(',',$PHONE_NUMBER)
);
$res = [];
array_walk($arr, function($v, $k) use (&$res){
 if($k % 2 == 0) //even
    $res['event'][] = ($k == 0) ? ($v.' : ') : ($k > 0 && $k < 4 ? $v.' - ' : $v);
else
    $res['odd'][]  =   ($k == 1) ? ($v.' : ') : ($k > 0 && $k < 4 ? $v.' - ' : 
$v);
 });
echo implode('',$res['event']).'<br/>';
echo implode('',$res['odd']).'<br/>';