我有办法在PHP的一个foreach循环中获取多个记录吗?

时间:2014-10-24 04:07:45

标签: php arrays

我有一个完全随机密钥的数组,例如:

$random_array = array (
    "randomtext" => "randomvalue",
    "apple" => "abc",
    "orange" => "bb",
    "someothertext" => "blue",
    "oxygen" => "bbaa",
    "someothertext" => "don't know what is this",
    "abcdef" => "bbcc",
    "someothertext" => "xxx",
)

因此,要遍历数组,foreach循环是必须的。但是,我想在每个循环中得到2条记录做一些处理。有办法吗?

1 个答案:

答案 0 :(得分:2)

如果你真的想要按两个元素处理元素,你也可以将它们分组/批处理。例如:

$random_array = array (
    "randomtext" => "randomvalue",
    "apple" => "abc",
    "orange" => "bb",
    "someothertext1" => "blue",
    "oxygen" => "bbaa",
    "someothertext2" => "don't know what is this",
    "abcdef" => "bbcc",
    "someothertext3" => "xxx",
);

$batches = array_chunk($random_array, 2, true); // batch them by twos, preverse the keys

echo '<pre>';
print_r($batches);

foreach($batches as $array) {
    foreach($array as $key => $value) {
        // do your process here, this will loop twice
    }
}

旁注:我必须修改你的数组,因为有些键是相同的。他们会覆盖他们没有改变。