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


Do I have a way to get multiple record in one foreach loop in PHP?

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

$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条记录来进行一些处理。有办法做到这一点吗?

如果你真的想按两个处理元素,你也可以按两个来块/批处理它们。示例:

$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
    }
}

旁注:我必须修改你的数组,因为有些键是相同的。它们将覆盖,但不会更改。