如何为两个数组设置foreach循环php
how to two array set foreach loop php
$color_arr = array("red","green","white");
$list_arr_two = array("a","b","c","d","e","f");
for ex -: a = red;
b = green;
c = white;
d = red;
e = green;
f = white;
我只需要在所有阵列颜色重复完成后获取重复颜色。
使用此自定义函数获取结果
$color_arr = array("red","green","white");
$list_arr_two = array("a","b","c","d","e","f");
print_r(ArrayMap($color_arr,$list_arr_two));
function ArrayMap($color_arr,$keyarray){
$newarr=array();
$total_array = count($color_arr);
foreach ($keyarray as $key => $value) {
$newarr[$value] = $color_arr[$key%$total_array];
}
return $newarr;
}
请尝试以下代码:
<?php
$color_arr = array("red","green","white");
$list_arr_two = array("a","b","c","d","e","f","sd");
$i=0;
$color_length = count($color_arr) -1 ;
foreach($list_arr_two as $key=>$val)
{
echo $colorCode = $color_arr[$i];
echo "<br/>";
$i++;
if($i > $color_length)
{
$i =0;
}
}
?>
带有条件的简单循环以重置使用颜色数组的索引。
<?php
$c = ["red","green","white"];
$l = ["a","b","c","d","e","f"];
$r = [];
$j = 0;
for ($i = 0; $i < count($l); $i++) {
$r[$l[$i]] = $j === count($c) ? $c[$j = 0] : $c[$j];
$j++;
}
print_r($r);
/* output
Array
(
[a] => red
[b] => green
[c] => white
[d] => red
[e] => green
[f] => white
)
*/
$color_arr = array("red","green","white");
$list_arr_two = array("a","b","c","d","e","f");
for ex -: a = red;
b = green;
c = white;
d = red;
e = green;
f = white;
我只需要在所有阵列颜色重复完成后获取重复颜色。
使用此自定义函数获取结果
$color_arr = array("red","green","white");
$list_arr_two = array("a","b","c","d","e","f");
print_r(ArrayMap($color_arr,$list_arr_two));
function ArrayMap($color_arr,$keyarray){
$newarr=array();
$total_array = count($color_arr);
foreach ($keyarray as $key => $value) {
$newarr[$value] = $color_arr[$key%$total_array];
}
return $newarr;
}
请尝试以下代码:
<?php
$color_arr = array("red","green","white");
$list_arr_two = array("a","b","c","d","e","f","sd");
$i=0;
$color_length = count($color_arr) -1 ;
foreach($list_arr_two as $key=>$val)
{
echo $colorCode = $color_arr[$i];
echo "<br/>";
$i++;
if($i > $color_length)
{
$i =0;
}
}
?>
带有条件的简单循环以重置使用颜色数组的索引。
<?php
$c = ["red","green","white"];
$l = ["a","b","c","d","e","f"];
$r = [];
$j = 0;
for ($i = 0; $i < count($l); $i++) {
$r[$l[$i]] = $j === count($c) ? $c[$j = 0] : $c[$j];
$j++;
}
print_r($r);
/* output
Array
(
[a] => red
[b] => green
[c] => white
[d] => red
[e] => green
[f] => white
)
*/