Ahoj, lze procházet dvě pole v jednom foreach? Pokud ano, jak? Díky moc
Fórum › PHP
Dvě pole, jedno foreach

Pokud to použiju takto:
foreach($_SESSION["polozky"] as $ip => $polozky)
{
foreach($_SESSION["kusy"] as $kusy)
{
echo "[".$ip."] ".$polozky." <".$kusy."> <br />";
}
}
tak se mi každý index pole "polozky" vypíše 2x, tudíž nevím, jak na to ...
Nerozumim. Kazdy index polozky se vypise tolikrat, kolik je kusu v $_SESSION["kusy"].
foreach(array(1,2,3,4,5) as $ip => $polozky)
{
foreach(array(1,2,3) as $kusy)
{
echo "[".$ip."] ".$polozky." <".$kusy."> <br />";
}
}
Vypise se celkem 5x3 radku 3x polozky. 11,12,13, 21,22,23, ... 51,52,53
#3 peter
Ne, takhle to nechci. Potřebuju, aby se každý index v poli "položky" vypsal normálně jednou ... ale zároveň potřebuju do jednoho echa vypsat hodnotu z pole "kusy", kde index bude stejný
takže:
echo "[".$_SESSION["polozky"][0]."], <".$_SESSION["kusy"][0].">";
s tím, že 0 je natvrdo a já potřebuju takto vypsat všechny pomocí foreach
Pokud nemáš v plánu mazat různé indexy, tak stačí použít while.
$i = 0;
while(isset($kusy[$i]). && isset($polozky[$i])){
echo $kusy[$i]." - ".$polozky[$i];
$i++;
}
Zasláno z mobilního telefonu.
#5 Markaos
Musel jsem to trochu upravit, ale pomohl jsi, diky :-)
Mám to teď takto:
$i = 0;
while(isset($_SESSION["polozky"][$i]) && isset($_SESSION["kusy"][$i]))
{
echo "Položka ".$_SESSION["polozky"][$i].", Kusy: ".$_SESSION["kusy"][$i]."<br />";
$i++;
}
A teď už jen poslední věc. Jak zjistit, jaký je to index, když to mám pomocí while a ne foreach?
Omlouvám se za triple post, ale někomu to může pomoct :-)
Nakonec jsem to vyřešil takto:
for($i = 0; $i < count($_SESSION["polozky"]); $i++)
{
if($_SESSION["polozky"][$i] == "" || $_SESSION["kusy"][$i] == "") continue;
echo "Hodnota pole: ".$_SESSION["polozky"][$i].", Index pole: ".$i.", Kusy: ".$_SESSION["kusy"][$i]."<br />";
}
Jestliže je hodnota prázdná, tak to přeskočí .. je to jakoby "smazaný" index, abych nemusel řešit problém s fcí unset :-)

Přidej příspěvek
Ano, opravdu chci reagovat → zobrazí formulář pro přidání příspěvku
×Vložení zdrojáku
×Vložení obrázku
×Vložení videa
































Uživatelé prohlížející si toto vlákno
Podobná vlákna
Potřeboval bych setřídit dvě pole o 2x1000000 prvcích — založil Blackknight
WHILE VE WHILU VE FOREACH — založil row
Cyklus foreach a while — založil Forest
Moderátoři diskuze