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

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])
        );
    }

图片转代码服务由CSDN问答提供 功能建议

我正在循环一个初始数组,并指定我想要的值。 然后我将我需要的值存储在一个数组中。 然后我将这些值组合成一个新的数组,包括键和值。 新数组仅存储已传递给它的所有数据的最后一个条目。

  $ exampleArray = array(); 
for($ i = 0; $ i&lt; 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 =&gt;  ; $ val)
 {
 $ secondExample [] = array(
“Field1”=&gt; $ val,
“Field2”=&gt; ucfirst($ A2 [$ i]),
“Field3”  =&gt; ucfirst($ A3 [$ i]),
“Field4”=&gt; ucfirst($ A4 [$ i]),
“Field5”=&gt; 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])
        );
    }
    
    点赞 评论
  • douzhang6496 2017-08-31 14:41

    As because you are overwriting every time the loop goes.Use array_push

     $secondExample = array();
    
    foreach( $A1 as $i => $val )
    {
        $varArray = array(
            "Field1" => $val,
            "Field2" => ucfirst($A2[$i]),
            "Field3" => ucfirst($A3[$i]),
            "Field4" => ucfirst($A4[$i]),
            "Field5" => ucfirst($A5[$i])
        );
        array_push($secondExample, $varArray);
    }
    
    点赞 评论

相关推荐 更多相似问题