how to calculate the sum of same array values in PHP - php

I have an array like this
$estimate[0]=>
'gear' =>'MMG'
'total' => 315
'efforts' => 9
'afh' => 18
$estimate[1]=>
'gear' =>'MMG'
'total' => 400
'efforts' => 2
'afh' => 6
$estimate[2]=>
'gear' =>'BOO'
'total' => 200
'efforts' => 20
'afh' => 16
$estimate[3]=>
'gear' =>'BOB'
'total' => 250
'efforts' => 20
'afh' => 16
I want to calculate the sum of total, efforts and afh in which gear is same and it will be stored in the another array. Following my coding is working when the array (estimate) size is less than 5.
$calculate = array();
for($et=0;$et<count($estimate);):
if($et==0):
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
endif;
for($cet=0;$cet<count($calculate);$cet++):
if($estimate[$et]['gear'] == $calculate[$cet]['gear']):
$calculate[$cet]['total'] = $calculate[$cet]['total'] + $estimate[$et]['total'];
$calculate[$cet]['efforts'] = $calculate[$cet]['efforts'] + $estimate[$et]['efforts'];
$calculate[$cet]['afh'] = $calculate[$cet]['afh'] + $estimate[$et]['afh'];
goto loopend;
endif;
endfor;
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
loopend:$et++;
endfor;
The coding is not working more than many gears. Sometimes it works. I can't find the issues. Please help me to solve the issues.

You might use array_reduce:
$result = array_reduce($estimate, function($carry, $item) {
if (!isset($carry[$item["gear"]])) {
$carry[$item["gear"]] = $item;
return $carry;
}
$carry[$item["gear"]]["total"] += $item["total"];
$carry[$item["gear"]]["efforts"] += $item["efforts"];
$carry[$item["gear"]]["afh"] += $item["afh"];
return $carry;
});
Demo

As per my comment use foreach loop when your array length is not define
Here is your desired code
<?php
$estimate = array(
"0" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"1" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"2" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
);
$gear=0;
$total=0;
$efforts=0;
$afh=0;
foreach ($estimate as $key => $value) {
$gear=$gear+$value['gear'];
$total=$gear+$value['total'];
$efforts=$gear+$value['efforts'];
$afh=$gear+$value['afh'];
}
echo "<pre>";
$result = array('gear' => $gear, 'total' => $total,'efforts' => $efforts,'afh' => $afh);
echo "<pre>";
print_r($result);
you can check the result HERE

<?php
$new_arr = array();
$estimate[0] =array(
'gear' =>'MMG',
'total' => 315,
'efforts' => 9,
'afh' => 18
);
$estimate[1]=array(
'gear' =>'MMG',
'total' => 400,
'efforts' => 2,
'afh' => 6,
);
$estimate[2]=array(
'gear' =>'BOO',
'total' => 200,
'efforts' => 20,
'afh' => 16,
);
$estimate[3]=array(
'gear' =>'BOB',
'total' => 250,
'efforts' => 20,
'afh' => 16,
);
foreach ($estimate as $key => $value) {
$new_arr[$value['gear']] = array(
'total' => (isset($new_arr[$value['gear']]['total']) ? ($new_arr[$value['gear']]['total'] + $value['total']) : $value['total'] ),
'efforts' => (isset($new_arr[$value['gear']]['efforts']) ? ($new_arr[$value['gear']]['efforts'] + $value['efforts']) : $value['efforts'] ),
'afh' => (isset($new_arr[$value['gear']]['afh']) ? ($new_arr[$value['gear']]['afh'] + $value['afh']) : $value['afh'] )
);
}
echo "<pre>";print_r($new_arr);

Related

How can I search an array for specific values?

I need some help with how I can search an array from a search box.
Lets say I search for the $ticker and write BTC
It will then print out:
The last known currency for BTC is 57
I only want it to print out $k3 values.
Appreciate if you could take your time and guide me in the right direction :)
<form method="POST" action="">
<input type="text" name="Searcharray" name="searcharray">
<input type="submit" value="Search" name="searcharray">
</form>
<?php
$ticker = array(
0 => "BTC",
1 => "ETH",
2 => "LTC",
3 => "XMR",
4 => "XRP"
);
$name = array(
0 => "Bitcoin",
1 => "Ethereum",
2 => "Litecoin",
3 => "Monero",
4 => "Ripple"
);
$k1 = array(
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5
);
$k2 = array(
0 => 11,
1 => 12,
2 => 13,
3 => 14,
4 => 15
);
$k3 = array(
0 => 17,
1 => 27,
2 => 37,
3 => 47,
4 => 57
);
?>
array_search would help - http://php.net/manual/de/function.array-search.php
$index = array_search('BTC', $ticker);
$value = $k3[$index];
Why dont you make such a structure?:
$data = [
'BTC' => [
'name' => 'Bitcoin',
'k1' => 1,
'k2' => 11,
'k3' => 17
], ...
];
then it would be:
$value = $data['BTC']['k3'];
$index = array_search("BTC", $ticker);
if ($index !== FALSE) {
$currency = $k3[$index];
echo "The last known currency of BTC is $currency";
}
But things would be easier if you used a 2-dimensional associative array:
$data = [
"BTC" => ["name" => "Bitcoin", "k1" => 1, "k2" => 11, "k3" => 17],
"ETH" => ["name" => "Ethereum", "k1" => 2, "k2" => 12, "k3" => 27],
...
];
Then you can do:
if (isset($data["BTC"])) {
$currency = $data["BTC"]["k3"];
echo "The last known currency of BTC is $currency";
}

Is there a simple way to manipulate bitwise enum in PHP?

I'm creating a custom user profile for a game (osu!) and I'm trying to get which "mods" has been used in a "top play".
The API provides a decimal number containing each mods the player used in his play.
Ex: 72 for DoubleTime+Hidden mods, since DoubleTime is 64 and Hidden 8
$hidden = 8;
$doubletime = 64;
$hiddendoubletime = ($hidden|$doubletime);
I want to, from 72 for example, know that its 8 and 64.
or even from 88 that it's 8 and 16 and 64.
I was thinking about transform 88 for example in binary (01011000), then detect all "1" positions since each "1" gives a mod.
Here : 01011000 -
the first "1" at position 4 is the Hidden mod, the second "1" a position 5 is the Hardrock mod and finally, the "1" at position 7 is the DoubleTime mod.
Then enum is the following :
enum Mods
{
None = 0,
NoFail = 1,
Easy = 2,
TouchDevice = 4,
Hidden = 8,
HardRock = 16,
SuddenDeath = 32,
DoubleTime = 64,
Relax = 128,
HalfTime = 256,
Nightcore = 512, // Only set along with DoubleTime. i.e: NC only gives 576
Flashlight = 1024,
Autoplay = 2048,
SpunOut = 4096,
Relax2 = 8192, // Autopilot
Perfect = 16384, // Only set along with SuddenDeath. i.e: PF only gives 16416
Key4 = 32768,
Key5 = 65536,
Key6 = 131072,
Key7 = 262144,
Key8 = 524288,
FadeIn = 1048576,
Random = 2097152,
Cinema = 4194304,
Target = 8388608,
Key9 = 16777216,
KeyCoop = 33554432,
Key1 = 67108864,
Key3 = 134217728,
Key2 = 268435456,
ScoreV2 = 536870912,
LastMod = 1073741824,
}
As you can see, the list is pretty big, so I can't just try each mods combinations in if() condition.
I would do something like this....
<?php
$user_options = 88;
$no_options = array ( 'None' => 0 );
$game_options = array (
'NoFail' => 1,
'Easy' => 2,
'TouchDevice'=> 4,
'Hidden' => 8,
'HardRock' => 16,
'SuddenDeath' => 32,
'DoubleTime' => 64,
'Relax' => 128,
'HalfTime' => 256,
'Nightcore' => 512,
'Flashlight' => 1024,
'Autoplay' => 2048,
'SpunOut' => 4096,
'Relax2' => 8192,
'Perfect' => 16384,
'Key4' => 32768,
'Key5' => 65536,
'Key6' => 131072,
'Key7' => 262144,
'Key8' => 524288,
'FadeIn' => 1048576,
'Random' => 2097152,
'Cinema' => 4194304,
'Target' => 8388608,
'Key9' => 16777216,
'KeyCoop' => 33554432,
'Key1' => 67108864,
'Key3' => 134217728,
'Key2' => 268435456,
'ScoreV2' => 536870912,
'LastMod' => 1073741824
);
$filtered = array_filter ( $game_options, function ( $value ) use ( $user_options )
{
return ( $value & $user_options ) == $value ? $value : NULL;
});
if ( empty ( $filtered ) )
{
print_r ( $no_options );
}
else
{
print_r ( $filtered );
}
?>
I was thinking, it would be best to only cycle through the user(s) set options, that way you don't have to cycle through all the game_options when maybe only a few lower numbered bits are set...
<?php
$user_options = 344;
$game_options = array (
'NoFail' => 1,
'Easy' => 2,
'TouchDevice'=> 4,
'Hidden' => 8,
'HardRock' => 16,
'SuddenDeath' => 32,
'DoubleTime' => 64,
'Relax' => 128,
'HalfTime' => 256,
'Nightcore' => 512,
'Flashlight' => 1024,
'Autoplay' => 2048,
'SpunOut' => 4096,
'Relax2' => 8192,
'Perfect' => 16384,
'Key4' => 32768,
'Key5' => 65536,
'Key6' => 131072,
'Key7' => 262144,
'Key8' => 524288,
'FadeIn' => 1048576,
'Random' => 2097152,
'Cinema' => 4194304,
'Target' => 8388608,
'Key9' => 16777216,
'KeyCoop' => 33554432,
'Key1' => 67108864,
'Key3' => 134217728,
'Key2' => 268435456,
'ScoreV2' => 536870912,
'LastMod' => 1073741824
);
function get_options ( $game_options, $user_options )
{
/* if no options are set, return this */
$nil = array ( 'None' => 0 );
/* if option(s) are set, return the array of set option(s) */
$set = array ( );
/* only loop the $game_options up until the max set $user_options */
$stop = $user_options;
foreach ( $game_options AS $on => $ov )
{
if ( $ov > $stop )
{
break;
}
else if ( ( $ov & $user_options ) == $ov )
{
$set[$on] = $ov;
$stop -= $ov;
}
}
return empty ( $set ) ? $nil : $set;
}
print_r ( get_options ( $game_options, $user_options ) );
?>

JSON php extract data (where a statement is true)

I'm trying to catch specific data from a weather forecast API request (JSON output). The request gives me data for the next 3 days but I only need the next day. Here a snippet of the output:
array (
'cod' => '200',
'message' => 0.00259999999999999988065102485279567190445959568023681640625,
'cnt' => 40,
'list' =>
array (
0 =>
array (
'dt' => 1526461200,
'main' =>
array (
'temp' => 292.93000000000000682121026329696178436279296875,
'temp_min' => 292.05000000000001136868377216160297393798828125,
'temp_max' => 292.93000000000000682121026329696178436279296875,
'pressure' => 1019.259999999999990905052982270717620849609375,
'sea_level' => 1029.170000000000072759576141834259033203125,
'grnd_level' => 1019.259999999999990905052982270717620849609375,
'humidity' => 71,
'temp_kf' => 0.88000000000000000444089209850062616169452667236328125,
),
'weather' =>
array (
0 =>
array (
'id' => 802,
'main' => 'Clouds',
'description' => 'scattered clouds',
'icon' => '03d',
),
),
'clouds' =>
array (
'all' => 36,
),
'wind' =>
array (
'speed' => 4.20000000000000017763568394002504646778106689453125,
'deg' => 37.00240000000000151203494169749319553375244140625,
),
'sys' =>
array (
'pod' => 'd',
),
'dt_txt' => '2018-05-16 09:00:00',
),
1 =>
array (
'dt' => 1526472000,
'main' =>
array (
'temp' => 293.6100000000000136424205265939235687255859375,
'temp_min' => 292.95800000000002683009370230138301849365234375,
'temp_max' => 293.6100000000000136424205265939235687255859375,
'pressure' => 1019.799999999999954525264911353588104248046875,
'sea_level' => 1029.65000000000009094947017729282379150390625,
'grnd_level' => 1019.799999999999954525264911353588104248046875,
'humidity' => 66,
'temp_kf' => 0.66000000000000003108624468950438313186168670654296875,
),
'weather' =>
array (
0 =>
array (
'id' => 803,
'main' => 'Clouds',
'description' => 'broken clouds',
'icon' => '04d',
),
),
'clouds' =>
array (
'all' => 56,
),
'wind' =>
array (
'speed' => 5.79999999999999982236431605997495353221893310546875,
'deg' => 38.0009000000000014551915228366851806640625,
),
'sys' =>
array (
'pod' => 'd',
),
'dt_txt' => '2018-05-16 12:00:00',
)
I'm trying to get the 'all' values where 'dt_txt' starts from 0am the next day to 0pam the day after.
For now I'm using the following php code without checking for dt_txt:
<?php
$url = "http://api.openweathermap.org/data/2.5/forecast?q=D%C3%BClmen,de&mode=json";
$response = file_get_contents($url);
$obj = json_decode($response);
$t = 0;
$regen = 0;
$regendiv = 0;
for($i=0; $i < 10; $i++) {
$fg = $obj->list[$i]->clouds->all;
$regen += $fg;
}
echo $regen;
?>
My code requires me to run the request at a specific time (like close to midnight) in order to catch the 'all' values for the next day. Is there any way to check for 'dt_text' = the next day?
My Idea would be something like this:
for($i=0; $i < 10; $i++) {
$fg = $obj->list[$i]->clouds->all;
if (strpos($obj->list[$i]->dt_txt), $date){
$regen += $fg;
}
**//But how do I get $date to be the following day**
}
echo $regen;
?>
I was able to solve it this way:
<?php
$nextWeek = time() + (24 * 60 * 60);
$morgen = date('Y-m-d', $nextWeek);
$url = "http://api.openweathermap.org/data/2.5/forecast?q=D%C3%BClmen,de&mode=json";
$response = file_get_contents($url);
$obj = json_decode($response);
$quote = 0;
for($i=0; $i < 14; $i++) {
if (strpos($obj->list[$i]->dt_txt, $morgen) !== false) {
$fg = $obj->list[$i]->clouds->all;
if($fg > 80) { $t = 1; }
$regen += $fg;
$quote++;
}
}
$regendiv = $regen / $quote;
?>
Probably not the prettiest way but it gets the job done.

remove duplicate array php

I have script like this
foreach ($onerow as $onekey => $dt ){
$arr = array();
foreach($row as $classkey => $classfoto):
$cek_class_foto = explode("/",$classfoto->name);
if($dt->foto_naam!=$cek_class_foto[1]){
$arr = array($dt->foto_naam);
print_r(array_unique($arr));
}
endforeach;
}
the output like this
Array ( [0] => _b101203.jpg )
Array ( [0] => _b101203.jpg )
my question is, how to remove this duplicates array?
Thank you
You are overwriting $arr for each iteration.
foreach ($onerow as $onekey => $dt ){
$arr = array();
foreach($row as $classkey => $classfoto):
$cek_class_foto = explode("/",$classfoto->name);
if($dt->foto_naam!=$cek_class_foto[1]){
$arr[] =$dt->foto_naam;
}
endforeach;
}
$arr = array_unique($arr);
$array1 = Array
(
'0' => Array
(
'messageId' => 9,
'userId' => 47,
'petId' => 68,
'message' => 'how hello',
'senderId' => 48,
'senderPetId' => 66,
'messageCreateTime' => '2015-07-31 11:44:59'
),
'1' => Array
(
'messageId' => 8,
'userId' => 49,
'petId' => 69,
'message' => 'pppppppppp',
'senderId' => 48,
'senderPetId' => 67,
'messageCreateTime' => '2015-07-31 11:15:16'
),
'2' => Array
(
'messageId' => 6,
'userId' => 48,
'petId' => 67,
'message' => 'gggg',
'senderId' => 49,
'senderPetId' => 69,
'messageCreateTime' => '2015-07-31 11:13:42'
),
'3' => Array
(
'messageId' => 2,
'userId' => 48,
'petId' => 67,
'message' => 'aaaaaaaa',
'senderId' => 47,
'senderPetId' => 68,
'messageCreateTime' => '2015-07-31 11:15:33'
)
);
/* code for removing last duplicate array within result array by KS */
/* matching between : userId, petId, senderId, senderPetId */
$temp_array = array();
$i = 0;
foreach($array1 as $key=>$value)
{
$FLAG = FALSE;
$temp_array = $array1[$key];
if($i==0)
{
$final_array[] = $temp_array;
}
else
{
for($j=0;$j<count($final_array);$j++)
{
if(($final_array[$j]['userId']==$temp_array['userId'] && $final_array[$j]['petId']==$temp_array['petId'] && $final_array[$j]['senderId']==$temp_array['senderId'] && $final_array[$j]['senderPetId']==$temp_array['senderPetId']) ||
($final_array[$j]['userId']==$temp_array['senderId'] && $final_array[$j]['petId']==$temp_array['senderPetId'] && $final_array[$j]['senderId']==$temp_array['userId'] && $final_array[$j]['senderPetId']==$temp_array['petId']))
{
$FLAG = TRUE;
}
}
if($FLAG == FALSE){
$final_array[] = $temp_array;
}
}
$i++;
}
print('<pre>');
print_r($final_array);
enter code here

php array operations

I have the following 2D array and I would like to compare some values. First I would like to get the highest value from the array and depends on time extract from the previous value with the same index.
example: highest(work_something(223))-previous(work_something(120))
$data = array(
0 => array(
'time' => '2011-10-03 18:43:00',
),
1 => array(
'time' => '2011-10-03 18:44:00',
),
2 => array(
'time' => '2011-10-03 18:45:00',
'item_something' => -17,
'keyword_something' => 0,
'keyword_something_1' => 0,
'search_something' => 0,
'search_links_something' => 0,
'work_something' => 120,
),
3 => array(
'time' => '2011-10-03 18:45:00',
'item_something' => -17,
'keyword_something' => 0,
'keyword_something_1' => 0,
'search_something' => 0,
'search_links_something' => 0,
'work_something' => 223,
),
);
$array //This is your 2D array
$highest = 0;
foreach($array as $key => $value):
if(isset($value['work_something'])){
if($value['work_something'] > $highest){
$highest = $value['work_something']; //This is highest 'work_something' value
$highest_array_key = $key; //This is the key of 'work_something' array
}
}
endforeach;
//To compare with previews element use
$array[$highest_array_key - 1] //this is prew element
example: highest(work_something(223))-previous(work_something(120))
$highest - $array[$highest_array_key - 1]['work_something'];

Categories