Reputation: 4682
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 ?
Upvotes: 0
Views: 51
Reputation: 8079
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
Upvotes: 0
Reputation: 967
Its not getting inserted to 0th index because you are using $new_array[] which creates a new index each time it is called. You can use fixed index by incrementing a counter in your loop or by calling this once each iteration. Your counter solution will look as follows:
$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++;
}
Upvotes: 1
Reputation: 152216
You can try with:
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;
}
Upvotes: 1