如何在php中使用foreach循环向另一个数组的每个元素添加一个数组元素?
清楚了解附加屏幕截图。 在索引1的这个图片元素中将添加到另一个数组的所有元素。那么索引2处的元素将被添加到另一个数组的每个元素,依此类推......
答案 0 :(得分:0)
尝试这样:
$mainArray = array("11","12","13"....);
$returnArray = array();
foreach($mainArray as $key => $value){
$subArray = array();
//Create the sub array here as you want it.
$subArray[] = $key + 1;
$subArray[] = $key + 2;
$subArray[] = $key + 3;
$subArray[] = $key + 4;
$subArray[] = $key + 5;
$subArray[] = $key + 6;
$returnArray[$value] = $subArray;
}
答案 1 :(得分:0)
请查看以下代码。
<?php
$arr = array(11,12,13,14,15);
$arrAnotherArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$subArrLen = count($arrAnotherArray);
foreach($arr as $key => $value){
$arr[$key] = array();
$sum = 0;
foreach($arrAnotherArray as $key1=>$val){
$sum = $value + $val;
array_push($arr[$key],$sum);
}
}
echo "<pre>";
print_r($arr);
echo "</pre>";
?>
答案 2 :(得分:0)
我不明白你希望如何格式化你的输出,但这里是加法逻辑...
$main = range(11,14);
$sub = range(1,6);
$output = [];
foreach ($main as $mainNumber) {
foreach ($sub as $subNumber) {
$output[$mainNumber . '+' . $subNumber] = $mainNumber + $subNumber;
}
}
var_dump($output);