php
  • foreach
  • 2013-08-23 66 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); 
    } 
    

    这将同时处理关联和数字数组。

    相关问题