如何抵消foreach循环中的开始?

时间:2015-08-21 07:45:59

标签: php foreach

我希望我foreach的{​​{1}}启动前:$Element = 10 ,最多 20

目前:

foreach($lang['tech'] as $Element => $ElementName)
    {
       $parse['tt_name'] = $ElementName; // Displays the name

       if($Element > 99) // At over 99 foreach stop
       {
           break;  
       }
    }

我希望我有这个原则:

foreach($lang['tech'] as **$Element(10 to 20)** => $ElementName) // Display Element 10 to 20
    {
       $parse['tt_name'] = $ElementName; // Displays the name
    }

感谢您的帮助

7 个答案:

答案 0 :(得分:3)

如果我理解你是正确的,你想只将元素10循环到20,你可以使用for循环

for($i = 10; $i <= 20;$i++) {
    $entry = $lang['tech'][$i];
    // do something
}

答案 1 :(得分:1)

您可以使用/

value

或者您可以使用continue循环:

foreach($lang['tech' as $Element => $ElementName)
{
   if($Element < 10) // Less than 10 - skip!
   {
       continue;  
   }

   $parse['tt_name'] = $ElementName; // Displays the name

   if($Element > 99) // At over 99 foreach stop
   {
       break;  
   }
}

答案 2 :(得分:0)

在你的foreach循环中

你错过了

foreach($lang['tech'] as $Element => $ElementName)
                    ^

答案 3 :(得分:0)

您在示例代码中的两个位置缺少]

foreach($lang['tech'] as $Element => $ElementName)
                    ^

foreach($lang['tech'] as **$Element(10 to 20)** => $ElementName)
                    ^

答案 4 :(得分:0)

您可以在迭代前过滤它:

$tech = array_filter($lang['tech'], function($key) {
    return $key >= 10 && $key <= 20;
}, ARRAY_FILTER_USE_KEY);

foreach ($tech as $key => $name) {
    // do what you need
}

答案 5 :(得分:0)

if(count($results)>0){
                   $headerLine = implode(',',array_keys($results[0]));

                    dump($headerLine);

                    if(!file_put_contents($filePath, $headerLine.PHP_EOL)){
                        throw new Exception("Cannot write FILE: {$filePath}");                    
                    }

                    foreach($results as $row){   
                        foreach($row as $k=>$v){
                            if($row[$k] == '0000-00-00 00:00:00'){$row[$k] = '';}
                            $row[$k] = trim(str_replace(array(',', "\n", "\r"), ' ', $row[$k]));
                        }

                        //ADDs content to file
                        if(!file_put_contents($filePath, implode(',', $row).PHP_EOL, FILE_APPEND)){
                            throw new Exception("Cannot write FILE: {$filePath}");                    
                        }
                    }

                    //check file size created                
                    $fileSize = filesize($filePath);
                    $reportString   = "Created file at: $filePath of ($fileSize)";
                    //report
                    print($reportString);

                    RETURN TRUE;                            
                }

答案 6 :(得分:0)

您可以循环进入subarray

foreach( array_slice ($yourarray , 10, 10) as $Element) {
...
}