2010-04-15 4 views
1

Dire que j'ai ces 3 tableaux:Comment lier des tableaux?

Product(milk,candy,chocolate) 
Colors(white,red,black) 
Rating(8,7,9) 

Comment créer une boucle pour lier ces tableaux si je reçois 3 variables dans chaque boucle: $product$color$rating

Ainsi par exemple, je sortie comme ceci:

lait est blanc et a une cote de /10

bonbons est rouge et a une cote de /10

chocolat est noir et a une cote de /10

Merci

+0

..et il n'y a aucun moyen que vous pouvez structurer/récupérer comme 'array (array ('lait', 'blanc', 8), array ('bonbons ',' rouge ', 7), ....) 'en premier lieu? – VolkerK

+0

Non il n'y a aucun moyen :( – Emily

Répondre

3

SPL Je ne sais pas si je bien. Mais voulez-vous quelque chose comme ça?

$products = array("milk", "candy", "chocolate"); 
$colors = array("white", "red", "black"); 
$ratings = array(8, 7, 9); 

for($i = 0; $i < sizeof($products); $i++) { 
    $product = $products[$i]; 
    $color = $colors[$i]; 
    $rating = $ratings[$i]; 

    echo $product . ' is ' . $color . ' and has a rating of ' . $rating . '/10 <br/>'; 
} 

sortie serait:

milk is white and has the rating of 8/10 
candy is red and has the rating of 7/10 
chocolate is black and has the rating of 9/10 
8

Eg en utilisant MultipleIterator

<?php 
$Product=array('milk','candy','chocolate'); 
$Colors=array('white','red','black'); 
$Rating=array(8,7,9); 

$it = new MultipleIterator; 
$it->attachIterator(new ArrayIterator($Product)); 
$it->attachIterator(new ArrayIterator($Colors)); 
$it->attachIterator(new ArrayIterator($Rating)); 

foreach($it as $e) { 
    echo join(' - ', $e), "\n"; 
} 

empreintes

milk - white - 8 
candy - red - 7 
chocolate - black - 9 
+0

C'est très bien rangé, je l'aime –

+0

Wow, jamais entendu parler de MultipleIterator, j'ai besoin d'étudier la bibliothèque SPL plus, merci! –