php
  • foreach
  • 2013-08-23 110 views -2 likes 
    -2

    我有這個PHP foreach循環:使用2個循環在PHP的foreach(...)

    foreach($emails_list as $email) 
    

    ,但我想這樣做

    foreach($emails_list as $email and $forename_list as $forename) 
    

    我的代碼foreach循環上面:

    $sql2="SELECT * from contacts where company_sequence = '".$customersequence."' and contactstatus = '' "; 
          $rs2=mysql_query($sql2,$conn) or die(mysql_error()); 
          while($result2=mysql_fetch_array($rs2)) 
          { 
           $emails_list[] = $result2["email"]; 
          } 
    

    SI我希望能夠在循環中包括$result["forename"];

    將上述工作做成2個循環?如果

    +0

    如果數組的順序相同,可以使用'array_combine'來創建一個數組。 –

    +3

    你想要做什麼?你的數組是什麼樣子的?爲什麼你需要在同一個循環中訪問兩者?解釋實際問題,而不是你如何解決它。也許SPL多重播放器可能會有所幫助;但除非你解釋我們不知道該怎麼勸告,只能猜測 –

    +0

    看我的編輯.... – user2710234

    回答

    0

    不知道理解的,但儘量使用for代替:

    $emails_list = array("[email protected]", "[email protected]", "[email protected]", "[email protected]"); 
    $forename_list = ("01 something", "02 something", "03 something", "04 something"); 
    
    if($emails_list == $forename_list){ 
        $count = count($emails_list); 
    
        for($i=0;$i<$count;$i++){ 
        echo 'Email: '.$emails_list[$i].', Name: '.$forename_list[$i]; 
        } 
    } else { echo 'Troubles'; } 
    
    +0

    你不應該在循環init中使用count($ emails list)來提高性能 – Sugar

    +0

    你的建議是什麼,而不是'count'? – M1K1O

    +2

    '$ count_temp = count($ emails_list);' 然後在循環中使用'$ count_temp',所以每次循環都不會再次計數。 – Sugar

    0

    沒有辦法爲這個使用for循環像

    for ($i=0;$i<=count($emails_list); $i++) { 
    echo $emails_list[$i]; 
    echo $forename_list[$i]; 
    } 
    
    爲此在的foreach在一個statment

    +0

    你不應該在循環init中使用count($ emails list)來提高性能 – Sugar

    +0

    如果$ forename_list小於$ emails_list,那麼你會遇到麻煩 – pikand

    0

    所有用基本的for循環列出的例子對數值數組都適用,但是關聯數組呢? 做到這一點,最好的辦法是類似以下內容:

    $arr_1 = array('foo'=>'bar', 'fizz'=>'bang'); 
    $arr_2 = array('hello'=>1, 2=>'world'); 
    
    $array_size = count($arr_1); // NOTE: This assumes the arrays are of the same size. 
    
    // Reset the internal array pointers 
    reset($arr_1); 
    reset($arr_2); 
    
    for ($i = 0; $i < $array_size; $i++) { 
        $first_array_element = current($arr_1); 
        $second_array_element = current($arr_2); 
    
        // code here 
    
        next($arr_1); 
        next($arr_2); 
    } 
    

    這將同時處理關聯和數字數組。

    相關問題