PHP array to stars [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have array with values:
7.09, 5.63 , 5.35 , ...
I'm rounding them to 0.5 with:
round(x * 2) / 2;
Now I have 7, 6, 5.5
How can I make stars by these? Max stars 5. So I need to make 5 stars = highest array value, what's then? Sorry for my bad english. I don't know what should I do.
7 - 5 stars
6 - 4.5 stars
5.5 - 4 stars

$mArray = array(8,2,5,1);
$biggestNumber = max($mArray);
foreach($mArray as $index => $star){
$percent = $star / $biggestNumber * 100;
$mFinalArray[$index]['number'] = $star;
$mFinalArray[$index]['stars'] = $percent / 100 * 5;
}
print_r($mFinalArray);
Output :
Array
(
[0] => Array
(
[number] => 8
[stars] => 5
)
[1] => Array
(
[number] => 2
[stars] => 1.25
)
[2] => Array
(
[number] => 5
[stars] => 3.125
)
[3] => Array
(
[number] => 1
[stars] => 0.625
)
)
Also if you want round numbers, you could change the last line from
$mFinalArray[$index]['stars'] = $percent / 100 * 5;
to
$mFinalArray[$index]['stars'] = round($percent / 100 * 5);
Example output using round :
Array
(
[0] => Array
(
[number] => 8
[stars] => 5
)
[1] => Array
(
[number] => 2
[stars] => 1
)
[2] => Array
(
[number] => 5
[stars] => 3
)
[3] => Array
(
[number] => 1
[stars] => 1
)
)

If you just want to get an average of your first integers, out of 5, just do a conversion (use the max to get max value = 5 stars) :
max = 7.09
a = 7.09
b = 5.63
starsA = (a/max)* 5
starsB = (b/max)* 5
and then round these values to get your stars on that 10-point scale.

Related

how do I group this in array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
$db_string = "|1||3||1||5||1||3||8||1||10||2|2||13||2||15|";
$array = array_filter(explode("|", $db_string));
if(in_array("1", $array)){
echo"<li>
Honeymoon Packages
</li>";
}
RESULT is Coming
* Honeymoon Packages
* Honeymoon Packages
* Honeymoon Packages
* Honeymoon Packages
because in array 1 is there 4 times, how do I group this in array and print result one time without duplicate?
I do prefer splitting with a regex, so no empty values will ever occur.
$db_string = "|1||3||1||5||1||3||8||1||10||2|2||13||2||15|";
$array = preg_split('/\|/', $db_string, 0, PREG_SPLIT_NO_EMPTY);
Now the array has an element for each number in the listed order. With the help of array map we use the empty $data array and build a key for unique element. So we know how many entries are there per item.
$data = [];
array_map(function($e) use (&$data) { isset($data[$e]) ? $data[$e]++ : $data[$e] = 1; }, $array);
Array
(
[1] => 4
[3] => 2
[5] => 1
[8] => 1
[10] => 1
[2] => 3
[13] => 1
[15] => 1
)
You can use the keys to have each item uniquely.
print_r(array_unique(array_keys($data)));
Array
(
[0] => 1
[1] => 3
[2] => 5
[3] => 8
[4] => 10
[5] => 2
[6] => 13
[7] => 15
)

Sort an array of numbers into two arrays of equal length in PHP

I have an array of 20 different numbers which contains ranking of students.
I want to split this array into two sub arrays of equal length i.e 10
I also want the sum of all numbers within each array to be close.
For example, in sub-array A there could be a total sum of 56 and in sub-array B there could be a total sum of 57.
I am using PHP.
I sort the main array here and would like to assign index[0] to sub-array A and index[1] to sub-array B, and keep repeating this until both arrays are filled.
My approach works but i think its not great and not dynamic.
I interate through the main original array for [i] and then add that to the first sub-array, then I set i = i+2 so that I get every second value and store them in the first array.
I then remove the value at index[i] from the main array.
What is left over is now sub-array B.
$kids = array (8,5,6,9,3,8,2,4,6,10,8,5,6,1,7,10,5,3,7,6);
sort($kids);
$arrlength = count($kids);
for($x = 0; $x < $arrlength; $x++) {
echo $kids[$x];
echo "<br>";
}
$teamA = array();
$teamB = array();
$i = 0;
while ($i < $arrlength)
{
#echo $kids[$i] ."<br />";
array_push($teamA, $kids[$i]);
unset($kids[$i]);
$i += 2;
}
$teamB = $kids;
print_r($teamA);
print_r($teamB);
My Output is :
Array ( [0] => 1 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 6 [6] => 7 [7] =>
8 [8] => 8 [9] => 10 )
The sum here of all values is = 58
Array ( [1] => 2 [3] => 3 [5] => 5 [7] => 5 [9] => 6
[11] => 6 [13] => 7 [15] => 8 [17] => 9 [19] => 10 )
The sum here of all values is = 61
Any help is greatly appreciated. I have no real experience with PHP or its built in functions so sorry if this is a basic question. Thanks!
There is a built-in helper function of php, array_slice. You can read about it in the link I provided.
Here's how you can use in to achieve what you want:
$kids = array (5,7,6,8,3,8,2,4,6,10,8,5,6,10,7,6,5,3,7,6);
sort($kids);
$arrlength = count($kids);
$arrayA= array_slice($kids, 0, $arrlength / 2);
$arrayB= array_slice($kids, $arrlength / 2);
Output
// $arrayA
array:10 [▼
0 => 2
1 => 3
2 => 3
3 => 4
4 => 5
5 => 5
6 => 5
7 => 6
8 => 6
9 => 6
]
// $arrayB
array:10 [▼
0 => 6
1 => 6
2 => 7
3 => 7
4 => 7
5 => 8
6 => 8
7 => 8
8 => 10
9 => 10
]
Another approach for achieving what you asked
$kids = array(8,5,6,9,3,8,2,4,6,10,8,5,6,1,7,10,5,3,7,6);
sort($kids);
$teamA = array();
$teamB = array();
foreach($kids as $i => $kid){
if($i % 2){
array_push($teamA, $kid);
} else{
array_push($teamB, $kid);
}
}
It will generate the same output and sum as you want.

How can i remove a session in an array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to write a product basket for my website, but I can't remove an index from array. I wrote an array index below:
Array
(
[0] => Array
(
[urun_id] => 174
[urun_adi] => ANT-5527N - Dual Polarity Parabolic Dish Anten 4.8-6.1Ghz 27Dbi
[urun_fiyati] => 672
[urun_fiyati_kur] => TL
[urun_adeti] => 1
)
[1] => Array
(
[urun_id] => 149
[urun_adi] => Cloud Router Switch 16x SFP+(10G ) 1Gbit Eth
[urun_fiyati] => 1683
[urun_fiyati_kur] => TL
[urun_adeti] => 1
)
[2] => Array
(
[urun_id] => 175
[urun_adi] => ANT-5531N - Dual Polarity Parabolic Dish Anten 4.8-6.1Ghz 31Dbi
[urun_fiyati] => 694
[urun_fiyati_kur] => TL
[urun_adeti] => 1
)
)
You can use unset for this:
unset($array[2]); removes the element with index 2

Php apply discount to multiple products evenly

Im trying to figure something out. I want to apply coupon/discount amount to multiple products evenly.
For example if I have an array with 3 items
Array
(
[0] => stdClass Object
(
[id] => 1
[price] => 10.00
)
[1] => stdClass Object
(
[id] => 2
[price] => 20.00
)
[2] => stdClass Object
(
[id] => 3
[price] => 30.00
)
)
my coupon vale is 10 $ off
and I have tried this:
foreach ($array as $row) {
$data['price'] = ($row->price - 10 / 3) * 100
}
So basically I want to deduct from each item price proportionally total of 10 and end up with something like:
Array
(
[0] => stdClass Object
(
[id] => 1
[price] => 7.50
)
[1] => stdClass Object
(
[id] => 2
[price] => 17.50
)
[2] => stdClass Object
(
[id] => 3
[price] => 25.00
)
)
where total price sum is 50 instead original of 60
So, from the comments under the question, you want to distribute the coupon value proportionally (not evenly) to prices of all items. That's pretty easy, it's more a mathematical problem than a programming one.
Calculate x as coupon / sum(prices)
Iterate through all items and subtract x * item_price from item_price
That's it.
For your example (coupon = 10, prices = [10, 20, 30]), the result is:
x = 10 / 60 = 0.1666667
Subtract x * item_price from each item's item_price:
10 - 10 * 0.1666667 = 10 - 1.6666667 = 8.33333
20 - 20 * 0.1666667 = 20 - 3.3333333 = 16.6666
30 - 30 * 0.1666667 = 30 - 5 = 25
To verify: 1.666667 + 3.3333333 + 5 = 10

loop through multidimensional array and order sub-array by scores

I am trying to calculate the winning order of golfers when they are tied in a competition.
These golf competitions are using the "stableford" points scoring system, where you score points per hole with the highest points winning. Compared to normal golf "stroke play" where the lowest score wins (though this also has the countback system, only calculating the lowest score in the event of a tie...)
The rules are to use a "countback". i.e., if scores are tied after 9 holes, the best placed of the ties is the best score from the last 8 holes. then 7 holes, etc.
The best I can come up with is 2 arrays.
An array with all the players who tied in a given round. ($ties)
One which has the full score data in (referencing the database playerid) for all 9 holes. ($tie_perhole)
I loop through array 1, pulling data from array 2 and using the following formula to create a temporary array with the highest score:
$max = array_keys($array,max($array));
If $max only has 1 item, this player is the highest scorer. the loop through the first array is "by reference", so on the next iteration of the loop, his playerid is now longer in the array, thus ignored. this continues until there is only 1 playerid left in the first array.
However, it only works if a single player wins in each iteration. The scenario that doesn't work is if a sub-set of players tie on any iterations / countbacks.
I think my problem is the current structure I have will need the original $ties array to become split, and then to continue to iterate through the split arrays in the same way...
As an example...
The $ties array is as follows:
Array
(
[18] => Array
(
[0] => 77
[1] => 79
[2] => 76
[3] => 78
)
)
The $tie_perhole (score data) array is as follows:
Array
(
[18] => Array
(
[77] => Array
(
[9] => 18
[8] => 16
[7] => 14
[6] => 12
[5] => 10
[4] => 8
[3] => 6
[2] => 4
[1] => 2
)
[79] => Array
(
[9] => 18
[8] => 17
[7] => 15
[6] => 14
[5] => 11
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
[76] => Array
(
[9] => 18
[8] => 16
[7] => 14
[6] => 12
[5] => 10
[4] => 8
[3] => 6
[2] => 4
[1] => 2
)
[78] => Array
(
[9] => 18
[8] => 17
[7] => 15
[6] => 13
[5] => 11
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
)
)
So in this competition, player's 78 and 79 score highest on the 8th hole countback (17pts), so 1st and 2nd should be between them. Player 79 should then be 1st on the 6th hole countback (14pts, compared to 13pts). The same should occur for 3rd and 4th place with the 2 remaining other players.
There are other scenarios that can occur here, in that within a competition, there will likely be many groups of players (of different amounts) on different tied points through the leaderboard.
Also note, there will be some players on the leaderboard who are NOT tied and stay in their current outright position.
The basics of the working code I have is:
foreach ($ties as $comparekey => &$compareval) {
$tie_loop = 0;
for ($m = 9; $m >= 1; $m--) {
$compare = array();
foreach ($compareval as $tie) {
$compare[$tie] = $tie_perhole[$comparekey][$tie][$m];
}
$row = array_keys($compare,max($compare));
if (count($row) == 1) {
$indexties = array_search($row[0], $ties[$comparekey]);
unset($ties[$comparekey][$indexties]);
// Now update this "winners" finishing position in a sorted array
// This is a multidimensional array too, with custom function...
$indexresults = searchForId($row[0], $comp_results_arr);
$comp_results_arr[$indexresults][position] = $tie_loop;
$tie_loop++;
}
// I think I need conditions here to filter if a subset of players tie
// Other than count($row) == 1
// And possibly splitting out into multiple $ties arrays for each thread...
if (empty($ties[$comparekey])) {
break;
}
}
}
usort($comp_results_arr, 'compare_posn_asc');
foreach($comp_results_arr as $row) {
//echo an HTML table...
}
Thanks in advance for any helpful insights, tips, thoughts, etc...
Robert Cathay asked for more scenarios. So here is another...
The leaderboard actually has more entrants (player 26 had a bad round...), but the code i need help with is only bothered about the ties within the leaderboard.
Summary leaderboard:
Points Player
21 48
21 75
20 73
20 1
13 26
This example produces a $tie_perhole array of:
Array
(
[21] => Array
(
[75] => Array
(
[9] => 21
[8] => 19
[7] => 16
[6] => 14
[5] => 12
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
[48] => Array
(
[9] => 21
[8] => 19
[7] => 16
[6] => 13
[5] => 11
[4] => 9
[3] => 8
[2] => 5
[1] => 3
)
)
[20] => Array
(
[73] => Array
(
[9] => 20
[8] => 18
[7] => 16
[6] => 13
[5] => 11
[4] => 8
[3] => 6
[2] => 5
[1] => 3
)
[1] => Array
(
[9] => 20
[8] => 17
[7] => 16
[6] => 14
[5] => 12
[4] => 9
[3] => 7
[2] => 4
[1] => 2
)
)
)
In this example, the array shows that players 75 and 48 scored 21 points that player 75 will eventually win on the 6th hole countback (14pts compared to 13pts) and player 48 is 2nd. In the next tied group, players 73 and 1 scored 20 points, and player 73 will win this group on the 8th hole countback and finishes 3rd (18 pts compared to 17 pts), with player 1 in 4th. player 26 is then 5th.
Note, the $tie_loop is added to another array to calculate the 1st to 5th place finishing positions, so that is working.
Hopefully that is enough to help.
Ok, so I don't understand golf at all... hahaha BUT! I think I got the gist of this problem, so heres my solution.
<?php
/**
* Author : Carlos Alaniz
* Email : Carlos.glvn1993#gmail.com
* Porpuse : Stackoverflow example
* Date : Aug/04/2015
**/
$golfers = [
"A" => [1,5,9,1,1,2,3,4,9],
"B" => [2,6,4,2,4,4,1,9,3],
"C" => [3,4,9,8,1,1,5,1,3],
"D" => [1,5,1,1,1,5,4,5,8]
];
//Iterate over scores.
function get_winners(&$golfers, $hole = 9){
$positions = array(); // The score numer is the key!
foreach ($golfers as $golfer=>$score ) { // Get key and value
$score_sub = array_slice($score,0,$hole); // Get the scores subset, first iteration is always all holes
$total_score = (string)array_sum($score_sub); // Get the key
if(!isset($positions[$total_score])){
$positions[$total_score] = array(); // Make array
}
$positions[$total_score][] = $golfer; // Add Golpher to score.
}
ksort($positions, SORT_NUMERIC); // Sort based on key, low -> high
return array(end($positions), key($positions)); // The last shall be first
}
//Recursion is Awsome
function getWinner(&$golfers, $hole = 9){
if ($hole == 0) return;
$winner = get_winners($golfers,$hole); // Get all ties, if any.
if(count($winner[0]) > 1){ // If theirs ties, filter again!
$sub_golfers =
array_intersect_key($golfers,
array_flip($winner[0])); // Only the Worthy Shall Pass.
$winner = getWinner($sub_golfers,$hole - 1); // And again...
}
return $winner; // We got a winner, unless they really tie...
}
echo "<pre>";
print_R(getWinner($golfers));
echo "</pre>";
Ok... Now ill explain my method...
Since we need to know the highest score and it might be ties, it makes no sense to me to maintain all that in separate arrays, instead I just reversed the
golfer => scores
to
Tota_score => golfers
That way when we can sort the array by key and obtain all the golfers with the highest score.
Now total_score is the total sum of a subset of the holes scores array. So... the first time this function runs, it will add all 9 holes, in this case theres 3 golfers that end up with the same score.
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
)
[1] => 35
)
Since the total count of golfers is not 1 and we are still in the 9th hole, we run this again, but this time only against those 3 golfers and the current hole - 1, so we are only adding up to the 8th hole this time.
Array
(
[0] => Array
(
[0] => B
[1] => C
)
[1] => 32
)
We had another tie.... this process will continue until we reach the final hole, or a winner.
Array
(
[0] => Array
(
[0] => C
)
[1] => 31
)
EDIT
<?php
/**
* Author : Carlos Alaniz
* Email : Carlos.glvn1993#gmail.com
* Porpuse : Stackoverflow example
**/
$golfers = [
"77" => [2,4,6,8,10,12,14,16,18],
"79" => [3,5,7,9,11,14,15,17,18],
"76" => [2,4,6,8,10,12,14,16,18],
"78" => [3,5,7,9,11,13,15,17,18]
];
//Iterate over scores.
function get_winners(&$golfers, $hole = 9){
$positions = array(); // The score numer is the key!
foreach ($golfers as $golfer => $score) { // Get key and value
//$score_sub = array_slice($score,0,$hole); // Get the scores subset, first iteration is always all holes
$total_score = (string)$score[$hole-1]; // Get the key
if(!isset($positions[$total_score])){
$positions[$total_score] = array(); // Make array
}
$positions[$total_score][] = $golfer; // Add Golpher to score.
}
ksort($positions, SORT_NUMERIC); // Sort based on key, low -> high
return [
"winner"=> end($positions),
"score" => key($positions),
"tiebreaker_hole" => [
"hole"=>$hole,
"score"=> key($positions)],
]; // The last shall be first
}
//Recursion is Awsome
function getWinner(&$golfers, $hole = 9){
if ($hole == 0) return;
$highest = get_winners($golfers,$hole); // Get all ties, if any.
$winner = $highest;
if(count($winner["winner"]) > 1){ // If theirs ties, filter again!
$sub_golfers =
array_intersect_key($golfers,
array_flip($winner["winner"])); // Only the Worthy Shall Pass.
$winner = getWinner($sub_golfers,$hole - 1); // And again...
}
$winner["score"] = $highest["score"];
return $winner; // We got a winner, unless they really tie...
}
echo "<pre>";
print_R(getWinner($golfers));
echo "</pre>";
Result:
Array
(
[winner] => Array
(
[0] => 79
)
[score] => 18
[tiebreaker_hole] => Array
(
[hole] => 6
[score] => 14
)
)

Categories