2011-07-14 107 views
1

我試圖保存代碼,並在同一時間每個進行多個php。可能嗎。PHP foreach多個和

$holes9 = string(lots of information separated by,) 
$stroke = string(other info separated by,) 
$index = string(other info separated by,) 

     $holes9 = explode(",",$holes9); 
     foreach ($holes9 as $holes) { 
      echo '<div class="hole"><b>'.$holes.'</b></div> 
<div class="stroke"></div> 
<div class="index"></div> 
'; 
     }; 

正如你可以看到我的foreach只適用於$ holes9作爲$ holes。我如何獲得其他兩位信息。

+1

總是這3個字符串包含相同的元素co UNT? –

+1

列表是否都是相同的長度? – MeLight

+0

不要採取這種錯誤的方式,但你有沒有嘗試過學習PHP的基礎知識? –

回答

2

如果$holes$stroke$index具有相同「元素」 的量,它足以與單一foreach

$holes9 = string(lots of information separated by,) 
$stroke = string(other info separated by,) 
$index = string(other info separated by,) 

$holes9 = explode(",",$holes9); 
$stroke = explode(",",$stroke); 
$index = explode(",",$index); 

foreach ($holes9 as $id => $holes) { 
    echo ' 
     <div class="hole"><b>'.$holes9[$id].'</b></div> 
     <div class="stroke">'.$stroke[$id].'</div> 
     <div class="index">'.$index[$id].'</div> 
    '; 
}; 
+0

+1提供工作解決方案並注意不同的長度問題。 – rzetterberg

2

如果字符串是相同的分離長度的(即它們將具有相同數量的逗號,的),那麼你可以做這樣的:

$holes9 = 'lots, of information, separated, by a, comma'; 
$stroke = 'other, info, separated, by, a comma'; 
$index = 'another, info, string, separated by, a comma'; 

$holes9 = explode(',',$holes9); 
$strokes = explode(',', $strokes); 
$index = explode(',', $index); 

foreach ($holes9 as $id => $holes) { 
    echo '<div class="hole"><b>'.$holes.'</b></div>'. 
     '<div class="stroke">'.$strokes[$id].'</div>'. 
     '<div class="index">'.$index[$id].'</div>'; 
}; 
1
$holes9 = explode(",",$holes9); 
$stroke = explode(",",$stroke); // explode these as well 
$index = explode(",",$index); 

foreach ($holes9 as $n => $holes) // take advantage of referencing the numeric key 
{ 
    echo '<div class="hole"><b>'.$holes.'</b></div>'; 
    echo '<div class="stroke">'.$stroke[$n].'</div>'; 
    echo '<div class="index">'.$index[$n].'</div>'; 
} 

由於explode()將生成數字鍵,利用foreach獲取鍵和值的能力。第一回波使用值,然後再使用密鑰(在這種情況下$n)來引用相同的元素的索引在另外兩個陣列($stroke$index,假定這些將具有相同數目的元素。)

0

如果所有的列表的長度是一樣的,你可以這樣做:

$holes9 = string(lots of information separated by,) 
$stroke = string(other info separated by,) 
$index = string(other info separated by,) 

     $holes9 = explode(",",$holes9); 
     foreach ($holes9 as $key => $holes) { 
      echo '<div class="hole"><b>'.$holes.'</b></div> 
<div class="stroke">'.$stroke[$key].'</div> 
<div class="index">'.$index[$key].'</div> 
'; 
}; 
0

假設你的3個字符串包含相同數量的元素,你可以使用替代的foreach這樣的:

$holes9 = explode(",",$holes9); 
$stroke = explode(",",$stroke); 
$index = explode(",",$index); 

for($i =0; $i < ;$i++){ 

echo '<div class="hole"><b>'.$holes9[$i].'</b></div> 
<div class="stroke">'.$stroke[$i].'</div> 
<div class="index">'.$index[$i].'</div>'; 
}