doutenggu4070 2014-01-27 08:45
浏览 34
已采纳

向多维数组添加另一个值

I have an array like this :

  $total= [20140124] => Array
    (
        [abc] => 0.19287878787879
        [total] => 38
        [revenue] => 1232
        [clicks] => 1110
        [score]=>100
    )

[20140123] => Array
    (
        [abc] => 0.32898148148148
        [total] => 28
        [revenue] => 1142
        [clicks] => 1022
        [score]=>200
    )

Now I am preparing another array and checking some conditions like the following:

foreach($total as $t){
    $new_array[] = array(
       "total"=>$t->abc;
       "another_value"=>$t->revenue/$t->clicks;
    );
    if(some_condition){
        $new_array[] = array("total_score"=>$t->clicks+$t->score); 
    }
}

What I need is an array like

$new_array = 

[0] => Array
        (
            [total] => total_value
            [another_value] => anopther_value
            [total_score] => total_score_value

        )

    [1] => Array
        (
            [total] => total_value
            [another_value] => anopther_value
            [total_score] => total_score_value
        )
)

But I am not getting the total_score inserted to the 0th index. Instead the whole array is replaced with the values in the if condition. How can I get the total_score also with the other indexes ?

  • 写回答

3条回答 默认 最新

  • doubipiao1611 2014-01-27 08:49
    关注

    try this one:

    foreach($total as $t){
        $array_element = array();
        $array_element["total"] = $t["abc"];
        $array_element["another_value"] = $t["revenue"] / $t["clicks"];
        );
        if(some_condition){
            $array_element["total_score"] = $t["clicks"] + $t["score"]; 
        }
        $new_array[] = $array_element;
    }
    

    In your code you are adding an element to $new_array and then checking for that condition. So you are adding the next element, but not editing the first

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料