Php 重新洗牌foreach循环中的数组值
我正在foreach循环中添加其他值数组,这对我来说很好Php 重新洗牌foreach循环中的数组值,php,arrays,foreach,Php,Arrays,Foreach,我正在foreach循环中添加其他值数组,这对我来说很好 $i = true; $array = array('red', 'blue'); foreach($array as $key => & $value) { echo $value . '<br />'; if ($i === true) { $others = array('white', 'yellow'); foreach($others as $key
$i = true;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
echo $value . '<br />';
if ($i === true) {
$others = array('white', 'yellow');
foreach($others as $key => & $other_value) {
$array[] = $other_value;
}
}
$i = false;
}
但我想重新排列foreach循环中的数组值,需要如下输出
red
white
yellow
blue
如果没有一些严重的
array\u slice()
ing,您将无法在$array
上执行此操作。因此,只需将$result
分配给另一个数组,就可以在$array
的第一个和第二个元素之间插入$other
数组:
$i = true;
$array = array('red', 'blue');
foreach($array as $value) {
$result[] = $value; // here...
if ($i === true) {
$others = array('white', 'yellow');
foreach($others as $other_value) {
$result[] = $other_value; // and here...
}
}
$i = false;
}
如果需要(无论出于何种原因)
$array=$result
如果没有一些严重的数组切片()
,您将无法在$array
上执行此操作。因此,只需将$result
分配给另一个数组,就可以在$array
的第一个和第二个元素之间插入$other
数组:
$i = true;
$array = array('red', 'blue');
foreach($array as $value) {
$result[] = $value; // here...
if ($i === true) {
$others = array('white', 'yellow');
foreach($others as $other_value) {
$result[] = $other_value; // and here...
}
}
$i = false;
}
如果需要(无论出于何种原因)
$array=$result代码>冷的解决方案如下:
$array = array('red', 'blue');
$others = array('white', 'yellow');
$temp = array_combine($array,$others);
$final = array();
foreach($temp as $key => $value) {
array_push($final,$key,$value);
}
$array = $final;
一个很酷的解决方案是这样的:
$array = array('red', 'blue');
$others = array('white', 'yellow');
$temp = array_combine($array,$others);
$final = array();
foreach($temp as $key => $value) {
array_push($final,$key,$value);
}
$array = $final;
$i=true;
$array=array('red','blue');
foreach($key=>&$value作为数组){
回显$value.“
”;
如果($i==true){
$a1=$array;
$a2=数组($value);
$result=array_diff($a1,$a2);
$others=数组('white','yellow');
$array=array\u merge($others,$result);
}
$i=假;
}
$i=true;
$array=array('red','blue');
foreach($key=>&$value作为数组){
回显$value.“
”;
如果($i==true){
$a1=$array;
$a2=数组($value);
$result=array_diff($a1,$a2);
$others=数组('white','yellow');
$array=array\u merge($others,$result);
}
$i=假;
}
你所说的重新洗牌是什么意思?你从开始到结束迭代你的数组。在此迭代过程中执行任何类型的reshufling
,对我来说都是无用的,可能会导致不可预见的循环行为。顺便说一句,向数组添加新数组可以在一行代码中使用array\u merge
来完成。@JeffPuckettII在foreach中添加的数组我应该首先出现的是哪一个?排序中是否有任何结构?比如按字母顺序等等?您可以使用usort应用自定义排序函数。您所说的重新排列是什么意思?您可以从头到尾对数组进行迭代。在此迭代过程中执行任何类型的reshufling
,对我来说都是无用的,可能会导致不可预见的循环行为。顺便说一句,向数组添加新数组可以在一行代码中使用array\u merge
来完成。@JeffPuckettII在foreach中添加的数组我应该首先出现的是哪一个?排序中是否有任何结构?比如按字母顺序等等?您可以使用usort应用自定义排序函数。