我有一个与此类似的数组:
$stuff = array("a"=>"115","b"=>"0","c"=>"1","d"=>"0","e"=>"11","f"=>"326","g"=>"9","h"=>"1","i"=>"12","j"=>"0","k"=>"56");
我想做的是仅在键的字符串是连续的且它们的值小于10的情况下才将它们串联起来-请注意,这还包括将单个键的值也保持在10以下。我不需要保留实际值。换句话说,这种情况下的预期结果将是:
Array ( [0] => bcd [1] => gh [2] => j)
因此,可能只需要连接两个连续的键,或者可能需要更多(例如,多达5个)。我不确定如何在阵列中“向前看”以实现这一目标。
答案 0 :(得分:2)
您不需要前瞻,但请记住过去。
$consecutive = '';
foreach($stuff as $k => $v) {
if ($v < 10) // or what ever condition you need
$consecutive .= $k;
else {
if ($consecutive) $res[] = $consecutive; // if exist add it
$consecutive= ''; // and reset
}
}
if ($con) $res[] = $con; //adding last element if exist as @Joffrey comment
现在$res
将成为您的愿望输出
实时示例:3v4l