我有一个这样的数组:
$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
)
现在我正在准备另一个数组并检查以下条件:
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);
}
}
我需要的是像
这样的数组$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
)
)
但我没有将total_score插入第0个索引。相反,整个数组将替换为if条件中的值。如何使用其他索引获得total_score?
答案 0 :(得分:1)
您可以尝试:
foreach($total as $t){
$data = array(
'total' => $t['abc'],
'another_value' => $t['revenue'] / $t['clicks']
);
if(some_condition){
$data['total_score'] = $t['clicks'] + $t['score'];
}
$new_array[] = $data;
}
答案 1 :(得分:1)
它没有插入到第0个索引,因为你正在使用$ new_array [],每次调用它时都会创建一个新索引。您可以通过在循环中递增计数器或通过每次迭代调用一次来使用固定索引。您的计数器解决方案如下所示:
$count = 0;
foreach($total as $t){
$new_array[$count] = array(
"total"=>$t->abc;
"another_value"=>$t->revenue/$t->clicks;
);
if(some_condition){
$new_array[$count] = array("total_score"=>$t->clicks+$t->score);
}
$count++;
}
答案 2 :(得分:0)
试试这个:
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;
}
在您的代码中,您要向$new_array
和添加元素,然后检查该条件。所以你要添加下一个元素,但不要编辑第一个