doubo1871 2017-08-31 14:30
浏览 536
已采纳

php for和foreach循环只存储最后一个值

I am looping though one initial array, and specifying values i want. Then i am storing the values i need in an array. Then i am combining those values into a new array, with keys and values. The new array is only storing the last entry of all the data that has been passed to it.

$exampleArray = array();
for ($i = 0; $i < 100; $i++){
    $exampleArray[] = array(
        $A1 =  $Anotherarray[$i][25],
        $A2 = $Anotherarray[$i][26],
        $A3 = $Anotherarray[$i][24],
        $A4 = $Anotherarray[$i][27],
        $A5 = $Anotherarray[$i][28]
    );

    $secondExample = array();

    foreach( $A1 as $i => $val )
    {
        $secondExample[] = array(
            "Field1" => $val,
            "Field2" => ucfirst($A2[$i]),
            "Field3" => ucfirst($A3[$i]),
            "Field4" => ucfirst($A4[$i]),
            "Field5" => ucfirst($A5[$i])
        );
    }
  • 写回答

2条回答 默认 最新

  • dth981485742 2017-08-31 14:34
    关注

    You are declaring $secondExample as a new array on every iteration. Do it like this:

    $exampleArray = array();
    $secondExample = array();
    
    for ($i = 0; $i < 100; $i++){
        $exampleArray[] = array(
            $A1 = $Anotherarray[$i][25],
            $A2 = $Anotherarray[$i][26],
            $A3 = $Anotherarray[$i][24],
            $A4 = $Anotherarray[$i][27],
            $A5 = $Anotherarray[$i][28]
        );
    
        $secondExample[$i] = array();
        foreach( $A1 as $j => $val) {
            $secondExample[$i][] = array(
            "Field1" => $val,
            "Field2" => ucfirst($A2[$j]),
            "Field3" => ucfirst($A3[$j]),
            "Field4" => ucfirst($A4[$j]),
            "Field5" => ucfirst($A5[$j])
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python