My code looks like this:
$sql = $pdo->prepare('SELECT source_clicks,source_impr,source_spend FROM `statistic` WHERE camp_id =? AND date BETWEEN ? AND ?');
$sql->bindColumn('source_clicks',$source_clicks);
$sql->bindColumn('source_impr',$source_impr);
$sql->bindColumn('source_spend',$source_spend);
$sql->execute([$_POST['get_source_stat'],$date[0],$date[1]]);
while ( $sql->fetch()) {
$data = explode(',',$source_clicks);
print_r($data);
}
the output i get is:
Array ( [0] => 30 [1] => 30 [2] => 51 [3] => 108 ) Array ( [0] => 30 [1] => 30 [2] => 51 [3] => 228 )
i need to sum this arrays saving their keys and get something like this:
array ([0] => 60 [1] => 60 [2] => 102 [3] => 336)
Can you tell me how can i do it?
One way to do this would be to push each exploded $source_clicks value into an array, and then use array_sum and array_column to get the results e.g.
$data = array();
while ($sql->fetch()) {
$data[] = explode(',',$source_clicks);
}
$sums = array();
foreach (array_keys($data[0]) as $column) {
$sums[$column] = array_sum(array_column($data, $column));
}
print_r($sums);
Related
I need to make my array better.
I am getting data from database and i have milestones and milestone_parts. i want two-dimensional array. I need data of milestones in the first dimension and milestone_parts in the second dimension.
With this code:
$query = "
SELECT
a.id AS `milestone_id`,
a.titel AS `milestone_titel`,
a.client AS `client`,
a.verkocht_id AS `milestone_verkocht_id`,
b.id AS `milestonefase_id`,
b.titel AS `milestonefase_titel`,
b.milestone_id AS `milestonefase_milestone_id`,
b.omschrijving AS `milestonefase_omschrijving`
FROM `milestones` a
INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
WHERE a.verkocht_id = '99'
";
$result= $db->query($dbh, $query);
while ($row = $db->fetchassoc($result))
{
$stone = array($row['milestone_verkocht_id'], $row['milestone_id'], $row['milestone_titel'], $row['client']);
$fase = array($row['milestonefase_milestone_id'],$row['milestonefase_id'],$row['milestonefase_titel']);
$stone[] = $fase;
echo '<pre>'; print_r($stone); echo '</pre>';
}
I get this as result
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 10
[2] => string
)
)
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 11
[2] => string
)
)
but I need (with names) this:
Array
(
[milestone_verkocht_id] => 99 // This is project id
[milestone_id] => 6
[milestone_title] => string
[client] => string
[10] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 10
[milestone_title] => string
)
[11] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 11
[milestone_title] => string
)
[12] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 12
[milestone_title] => string
)
)
Can you help me or do you have a solution? Help me please!
you can cycle each field returned by the query, checking the field name and making new arrays
$stones = array();
while ($row = $db->fetchassoc($result)) {
$fase = array();
$stone = array('milestones' => array());
foreach ($row as $k => $v) {
if (strpos($k, 'milestonefase_') === 0) {
$fase[$k] = $v;
} else {
$stone[$k] = $v;
}
}
if(!isset($stones[$stone['milestone_id']])) {
$stones[$stone['milestone_id']] = $stone;
}
$stones[$stone['milestone_id']]['milestones'][$fase['milestonefase_id']] = $fase;
}
echo '<pre>'.print_r($stones, true).'</pre>';
Edit
made some changes in order to match the request. Now we use $stones to store the information we already have on a milestone, adding to it the different "$fase" returned from the query
Probably a more clean way is to retrieve all the information with two different queries one for milestones and the other for the fases
Edit2
Added a sub-array for the milestone fases
I am using Codeigniter and I have a function like this .
function total_income(){
$data['total_income'] = $this->mod_products->total_income();
echo"<pre>";
print_r($data['total_income']);
}
The above code return an array like this.
Array
(
[0] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[1] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[2] => stdClass Object
(
[sub_product_price] => 50
[quantity] => 15
)
[3] => stdClass Object
(
[sub_product_price] => 500
[quantity] => 5
)
)
Now I want to get the [sub_product_price] and multiply that value with [quantity] .Then I want to get the array_sum. I don't have an idea how to do that. Could some one help me It would be grate ,
Cheers!! Rob
$sum = 0;
foreach ($array as $obj) {
$sum += ($obj->quantity * $obj->sub_product_price);
}
Add the all values after multiplication in an empty array and use array_sum() to get the final value.
$temp = array();
foreach($data['total_income'] as $in)
{
$temp[] = $in->sub_product_price * $in->quantity;
}
$total = array_sum($temp);
Explanation:
array_sum() returns the sum of all the values of an array.
Example,
$array = array(4,5,6);
echo array_sum($array); // 15
My array is
Array
(
[0] => Array
(
[id] => 20
[new_id] => 958
[affiliate_id] => 33
)
[1] => Array
(
[id] => 21
[new_id] => 959
[affiliate_id] => 45
)
[2] => Array
(
[id] => 22
[new_id] => 960
[affiliate_id] => 23
)
[3] => Array
(
[id] => 23
[new_id] => 961
[affiliate_id] => 33
)
)
and i want array
Array
(
[0] => Array
(
[id] => 20
[new_id] => 958
[affiliate_id] => 33
)
[1] => Array
(
[id] => 21
[new_id] => 959
[affiliate_id] => 45
)
[2] => Array
(
[id] => 22
[new_id] => 960
[affiliate_id] => 23
)
)
I want to remove duplicates value of affiliate_id . According to first array i am getting affiliate_id's value is 33 for two time. But i want it for one time. So in my second array (which will be my answer) i remove it.
Try something like this, not so pretty as array_ one liners, but still:
$existing_aff_ids = array();
$unique = array();
foreach ($affiliate as $aff) {
if (!isset($existing_aff_ids[$aff['affiliate_id']])) {
$unique[] = $aff;
$existing_aff_ids[$aff['affiliate_id']] = 1;
}
}
Given $affiliates as in your answer, looping over the array and checking for affiliate_id would do the trick
$unique_affiliates = array();
foreach($affiliates as $affiliate) {
$affiliate_key = $affiliate['key'];
/* Variant 1 */
$unique_affiliates[$affiliate_key] = $affiliate;
/* Variant 2 */
if(!isset($unique_affiliates[$affiliate_key])) {
$unique_affiliates[$affiliate_key] = $affiliate;
}
}
All entries in $unique_affiliates will have unique affiliate_keys. Variant 1 will contain the last occurrence of each afffiliate_key (as in your example), whereas variant 2 will add the first occurrence of any affiliate_key and just ignore all subsequent ones.
These are not duplicate values :
1. $input = array_map("unserialize",
array_unique(array_map("serialize", $data))
2. array_values(array_unique($data))
Both this case fails because of the unique id values are there it requires all values to be same to consider it as duplicate.
Solution:Will making the array check the value of the corresponding field.
foreach($data as $key=>$val)
{
if (is_array($val))
{
$val2 = arrayUnique($val);
}
else
{
$val2 = $val;
$newArray=array_unique($data);
$newArray=deleteEmpty($newArray);
break;
}
if (!empty($val2))
{
$newArray[$key] = $val2;
}
}
print_r($newArray);
I am trying to sort an array sent from an XML feed.
The Array looks like this from print_r($answer);:
Array
(
[size] => Array
(
[0] => 1.5m x 1.5m
[1] => 1.5m x 3m
[2] => 3m x 6.0m
[3] => 3m x 2.3m
)
[rate] => Array
(
[0] => 80
[1] => 135
[2] => 295
[3] => 180
)
[sortorder] => Array
(
[0] => 3
[1] => 4
[2] => 1
[3] => 2
)
.
.
.
)
I want to get out the array:
Array
(
[size] => Array
(
[0] => 3m x 6.0
[1] => 3m x 2.3m
[2] => 1.5m x 1.5m
[3] => 1.5m x 3m
)
[rate] => Array
(
[0] => 295
[1] => 180
[2] => 80
[3] => 135
)
[sortorder] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
.
.
.
)
What I am trying to do is use the Sort Order sub array to display the items in that order
I have tried a number of uasort() and array_multisort() examples, but all seem to order the sub arrays and not the values inside the sub arrays
Any ideas will be a great help. Cheers
This one sorts $answer['sortorder'] and uses those keys to sort the rest of $answer without restructuring first.
// sort $answer['sortorder'] and retrieve indices.
asort($answer['sortorder']);
$idx = array_keys($answer['sortorder']);
// do sorting
$sorted = array();
foreach($answer as $key=>$subarr) {
if ($key != 'sortorder') { // don't sort
foreach($idx as $i) {
$sorted[$key][] = $subarr[$i];
}
} else {
// $answer['sortorder'] is already sorted.
$sorted[$key] = $subarr;
}
}
print_r($sorted);
See it in action here.
This approach will re-structure the array with the sort order being the index, sort the array, then return it to it's original structure.
echo '<pre>';
$array['size'][0] = '1.5m x 1.5m';
$array['size'][1] = '1.5m x 3m';
$array['size'][2] = '3m x 6.0m';
$array['size'][3] = '3m x 2.3m';
$array['rate'][0] = 80;
$array['rate'][1] = 135;
$array['rate'][2] = 295;
$array['rate'][3] = 180;
$array['sortorder'][0] = 3;
$array['sortorder'][1] = 4;
$array['sortorder'][2] = 1;
$array['sortorder'][3] = 2;
$temp = array();
foreach($array['sortorder'] as $key => $value)
{
$temp[$array['sortorder'][$key]] = array(
'size'=>$array['size'][$key],
'rate'=>$array['rate'][$key],
'sortorder'=>$array['sortorder'][$key]
);
}
ksort($temp);
$array = array();
foreach($temp as $key => $value)
{
$array['size'][] = $value['size'];
$array['rate'][] = $value['rate'];
$array['sortorder'][] = $value['sortorder'];
}
print_r($array);
May I propose to use a different array structure that bundles each size, rate and sort order into one item:
array(
array('size' => '...', 'rate' => '...', 'sort order' => '...'),
...
)
That makes it trivial to sort, and in fact easier to work with in general.
This PHP 5.3+ code does this transformation and sorting:
$answer = array_map(function ($size, $rate, $sortorder) {
return compact('size', 'rate', 'sortorder');
}, $answer);
usort($answer, function ($a, $b) { return $a['sortorder'] - $b['sortorder']; });
I have the following array for tire sizes:
Array
(
[0] => 155
[1] => 70
[2] => 13
)
Array
(
[0] => 155
[1] => 80
[2] => 13
)
Array
(
[0] => 165
[1] => 65
[2] => 14
)
Array
(
[0] => 175
[1] => 65
[2] => 14
)
Array
(
[0] => 175
[1] => 70
[2] => 13
)
Array
(
[0] => 175
[1] => 70
[2] => 14
)
and so on. Now I am creating a drop down so people can select the tire size they are searching for. so here is my PHP code:
include 'database.php';
$result = $mysqli->query('SELECT DISTINCT SKU_SIZE FROM SKU_DATA WHERE SKU_BRANDNAME = "'.$brand.'" ORDER BY SKU_SIZE');
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
echo "<option>".$chars[0]."</option>";
}
Now that code is just showing the first number in each array, for the very first drop down they select.
Right now it is showing 155, 155, 165, 175, 175 - and what I want it to do is just show the unique values so it would just show 155, 165, 175.
Update: Thanks! I got that part working. One quick question.. the order is not quite right, not sure what I am doing wrong. Here is a preview:
Create an array and check to see if each value is in the array before outputting it. If it is not in the array, add it in before outputting.
include 'database.php';
$result = $mysqli->query(
'SELECT DISTINCT SKU_SIZE
FROM SKU_DATA WHERE SKU_BRANDNAME = "'.$brand.'"
ORDER BY SKU_SIZE'
);
$seen = array();
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
if(in_array($chars[0], $seen))
continue;
$seen[] = $chars[0];
echo "<option>".$chars[0]."</option>";
}
You can remove any duplicate unique items from an array using the array_unique() function.
EG:
$arrays = array(1,2,3) + array(1,2,3);
print_r(array_unique($arrays));
// Will print just: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
use this:
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
$sizes[$chars[0]] = true;
}
ksort($sizes, SORT_NUMERIC);
foreach ($sizes as $size => $tmp){
echo "<option value=\"$size\">$size</option>";
}
Use a temporary array to store the numbers that have been echoed then.
Make a new array with just the first value
$diameter = array();
foreach ($tires as $tire) {
$diameter[] = $tire[0];
}
Then, use array_unique() to remove the duplicates, or only add them to $diameter if they are not already in there.
Then use that $diameter array to create the dropdown.
This has the advantage that you can also sort the $diameter array.