我正在尝试遍历数组并返回按模式排序的值(两个组)。我的抽象数学技能让我失望。我很难过,我无法弄清楚这种模式。这是我到目前为止所拥有的。
$ars = array(
0 => "red",
1 => "blue",
2 => "green"
3 => "yellow",
4 => "purple"
5 => "black",
6 => "white",
7 => "orange"
);
$group_1 = '';
$group_2 = '';
foreach ( $ars as $ar ) :
if ($ar == 0 || $ar == 1 ) :
$group_1 .= $ar;
elseif ($ar == 2 || $ar == 3) :
$group_2 .= $ar;
elseif ($ar == 4 || $ar == 5) :
$group_1 .= $ar
elseif ($ar == 6 || $ar == 7) :
$group_2 .= $ar;
endif;
endforeach;
echo group_1; //result (red,blue,purple,black)
echo group_2; //result (green,yellow,white,orange)
无法创建有效的foreach语句,该语句将对可变数量的$ ars进行排序并在此分组中返回它们。任何帮助将不胜感激。
答案 0 :(得分:1)
$ars = array(
"red",
"blue",
"green",
"yellow",
"purple",
"black",
"white",
"orange"
);
$array1 = array();
$array2 = array();
for($i=0;$i<count($ars);$i++){
if ($i%4>=2)$array2[] = $ars[$i];
else $array1[] = $ars[$i];
}
print_r($array1);
print_r($array2);
哎呀,太晚了。但也许将项目排序为数组更好?