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 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?
  • ¥50 复现论文;matlab代码编写