I want to create leveling system with Codeigniter.
I retrieve all criteria from the table, then User fill the quistionare and finally system make a decission, level 1, level 2, or level 3.
Here is my controller:
if ($this->input->post('submit_asesmen')) {
$hitung_asesmen=count($_POST['id_komponen']);
$level='';
for ($i=0; $i < $hitung_asesmen; $i++) {
$id_asesmen=$_POST['id_komponen'][$i];
$yes=$_POST['yesorno'][$i];
$bukti=$_POST['cek'][$i];
$lihat_level=$this->m_asesmen->select_level($id_asesmen);
$data_asesmen = array(
'id_komponen_asesmen' => $id_asesmen,
'yes_or_no' => $yes,
'level' => $lihat_level,
);
$hitung_level_1=$this->m_asesmen->jml_level_1();
$macam_level_1=$this->m_asesmen->macam_level_1();
if ($lihat_level=='1' && $yes=='1') {
echo "Level 1 <br>";
}
else{
echo "Level 0 <br>";
}
}
}
My temporary output is like
Level 1
Level 0
Level 0
Level 0
Level 1
Level 1
Level 1
Level 1
Level 0
Level 0
Level 0
How to create output like : ?
Level 0 : 6 values
Level 1 : 5 values
This can be achieved with PHP's function array_count_values(). Just pass your array to this function and it will return an associative array containing the value/count pairs.
Example:
$tempOutput = array('Level 1', 'Level 0', 'Level 0', 'Level 0', 'Level 1', 'Level 1', 'Level 1', 'Level 1', 'Level 0', 'Level 0', 'Level 0');
// will return array('Level 1' => 5, 'Level 0' => 6);
$newOutput = array_count_values($tempOutput);
Since in your code you do not save the values in an array, it would be a better and easier solution to manually count the values:
// array holding the counts for each level
$levels = [];
if ($this->input->post('submit_asesmen')) {
$hitung_asesmen=count($_POST['id_komponen']);
$level='';
for ($i=0; $i < $hitung_asesmen; $i++) {
$id_asesmen=$_POST['id_komponen'][$i];
$yes=$_POST['yesorno'][$i];
$bukti=$_POST['cek'][$i];
$lihat_level=$this->m_asesmen->select_level($id_asesmen);
$data_asesmen = array(
'id_komponen_asesmen' => $id_asesmen,
'yes_or_no' => $yes,
'level' => $lihat_level,
);
$hitung_level_1=$this->m_asesmen->jml_level_1();
$macam_level_1=$this->m_asesmen->macam_level_1();
if ($lihat_level=='1' && $yes=='1') {
echo "Level 1 <br>";
}
else{
echo "Level 0 <br>";
}
// check if a count exists in $levels
if(!isset($levels[$lihat_level])) {
// count does not exist, initialize with 1
$levels[$lihat_level] = 1;
} else {
// count already exists, increase by 1
$levels[$lihat_level] ++;
}
}
}
// And this will create the desired output like you wrote it in your question
foreach($levels as $level => $count) {
echo 'Level ' . $level . ' : ' . $count . ' values<br />';
}
Nice Example but it doesn't explain every well what he really wants
Try out this
Example
$arr = array("Level 1","Level 2","Level 3", "Level 4");
$newData = array_count_values($arr);
foreach($arr as $data){
echo $data.": ".$newData[$data]." value<br>";
}
Result
Level 1: 1 value
Level 2: 1 value
Level 3: 1 value
Level 4: 1 value
if ($this->input->post('submit_asesmen')) {
$hitung_asesmen=count($_POST['id_komponen']);
$level='';
// Define Level Array
$levels_ary=array();
for ($i=0; $i < $hitung_asesmen; $i++) {
$id_asesmen=$_POST['id_komponen'][$i];
$yes=$_POST['yesorno'][$i];
$bukti=$_POST['cek'][$i];
$lihat_level=$this->m_asesmen->select_level($id_asesmen);
$data_asesmen = array(
'id_komponen_asesmen' => $id_asesmen,
'yes_or_no' => $yes,
'level' => $lihat_level,
);
$hitung_level_1=$this->m_asesmen->jml_level_1();
$macam_level_1=$this->m_asesmen->macam_level_1();
if ($lihat_level=='1' && $yes=='1') {
$levels_ary[]="Level 1";
}
else{
$levels_ary[]="Level 0";
}
}
print_r(array_count_values($levels_ary));
}
Related
I am working in a scoring system in php. When user chooses specific question, get extra points.
If anyone has a working PHP demo with code of a scoring system, he would be welcome. I mostly need a working "for" function:
"for question 1, if answer is abc, 5 points, else 0 points. for question 2, if aswer is bcd, 10 points, if answer is cft, 10 points, else 0 points", etc.
I would not want to have to fill my code with endless if statements.
For my current attempt, The error it displays:
Fatal error: Uncaught Error: Call to undefined function value() in C:\xampp\htdocs\score.php:18 Stack trace: #0 {main} thrown in C:\xampp\htdocs\score.php on line 18
Edit: I realized i might not have defined the "value" variable. It should give the value of "1 point" for now. How should i define it?
<?php
// Define questions and the correct answers
$questions = array(
'AB01' => 3, // correct answer to question AB01 is 3
'AB02' => 1, // correct answer to AB02 is code 1
'AB03' => 4, // correct answer to AB03 is hidden behind code 4
'AB04' => 2,
'AB05' => 1
// and so on
);
// Initialize counter variable
$points = 0;
// Check all questions in a loop
foreach ($questions as $variable=>$correct) {
// Call up participant's answer
$answer = value($variable);
// Check and count point if applicable
if ($answer == $correct) {
$points++; // synonymous with $points = $points + 1
}
}
// Show result ...
html('<p>You have scored'.$points.' points.</p>');
// ... or store in an internal variable
put('IV01_01', $points);
// ...
// Check all questions in a loop
foreach ($questions as $variable=>$correct) {
if (value($variable) == $correct) {
$points++;
}
}
// Show result or otherwise process
// ...
// Define questions and the values of possible answers
$questions = array(
'AB01' => array(1 => 2, 2 => 5, 3 => 3), // In question AB01, answer 1 has value 2, 2 has value 5, 3 has value 3
'AB02' => array(1 => 5, 2 => 4, 3 => 1), // In question AB02, values 5 (answer 1), 4 (2) und 1 (3) are assigned
'AB03' => array(1 => 0, 2 => 0, 3 => 5),
'AB04' => array(1 => 4, 2 => 0, 3 => 3),
'AB05' => array(1 => 2, 2 => 2, 3 => 5),
// u.s.w.
);
// Initialize counter variable
$points = 0;
// By using foreach you can just pass through the key-value pairs
foreach ($questions as $variable => $values) {
// Call up participant's answer
$answer = value($variable);
// Check if there is a value available for this answer (otherwise, do not award a point)
if (isset($values[$answer])) {
// Count the value
$points += $values[$answer];
}
}
// Show result or otherwise process
html('<p>You have scored'.$points.' points.</p>');
$points = valueSum('AB01');
// Show result or otherwise process
html('<p>You have scored '.$points.' points.</p>');
// Call up list of all items
$items = getItems('AB01');
// Initialize points variable
$points = 0;
// Pass through all items
foreach ($items as $item) {
// Question ID still has to be assembled
$id = 'AB01_'.sprintf('%02d', $item);
// Call up participant's answer
$answer = value($id);
// An error code may have been saved (e.g. -1 for "no response")
// Otherwise, count the answer
if ($answer > 0) {
$points += $answer;
}
}
// Show result or otherwise process
html('<p>You have scored '.$points.' points.</p>');
$points += $answer - 1;
// List of items - providing polarity in each case
$items = array(
'01' => +1,
'02' => -1,
'03' => +1,
'04' => +1,
'05' => -1
// and so on.
);
// Initialization of points variable
$points = 0;
// Pass through all items
foreach ($items as $item => $polarity) {
// Here the variable ID is built from the question and item IDs
$id = 'AB01_'.$item;
// Call up respondent's answer
$answer = value($id);
// Ignore if it is not a valid response
if ($answer < 1) {
// This means the rest are ignored in the FOR/FOREACH loop
continue;
}
// "Invert" answers
if ($polarity < 0) {
// In a 5-point scale, the inverted answer code has a value of 6
// the constant has to be adjusted for other differentations.
$answer = 6 - $answer;
}
// Add up
$points += $answer;
}
// Show result or otherwise process.
html('<p>You have scored'.$points.' points.</p>');
if (
(value('AB01_01') == 2) and
(value('AB01_02') == 2) and
(value('AB01_03') == 1) and
(value('AB01_04') == 1)
) {
// Count point, jump to a different part, or just display a message
html('<p>Correct</p>');
} else {
html('<p>Incorrect</p>');
}
// Define questions and their correct answers
// Only items are defined that will also be checked
$questions = array(
// In question AB01, 1 and 2 have to be checked, 3 and 4 must not be checked
'AB01' => array(1 => 2, 2 => 2, 3 => 1, 4 => 1),
// In question AB02, 2 and 3 have to be checked, 4 must not, and the value for 1 is irrelevant
'AB02' => array( 2 => 2, 3 => 2, 4 => 1),
// In AB03, all 4 have to be checked
'AB03' => array(1 => 2, 2 => 2, 3 => 2, 4 => 2),
// and so on.
'AB04' => array(1 => 1, 2 => 2, 3 => 1, 4 => 2),
'AB05' => array(1 => 2, 2 => 1, 3 => 2 )
);
// Initialize counter variable
$points = 0;
// Pass through all questions
foreach ($questions as $questionId => $answers) {
// Set the error counter for this question to 0
$error = 0;
foreach ($answers as $itemId => $default) {
// Assemble item ID
$id = $questionId.'_'.$itemId;
// Call up participant's answer
$answer = value($id);
// Verify answer is correct (actually: for falsehood)
if ($answer != $default) {
// In the event of any deviation, count as an error
$error++;
}
}
// Check if the question has been correctly answered
if ($error == 0) {
// Award a point
$points++;
}
}
// Show result or otherwise process
html('<p>You have scored '.$points.' points.</p>');
if ($points < 10) {
text('feedback1');
} elseif ($points < 20) {
text('feedback2');
} else {
text('feedback3');
}
$type = valueMean('AB01');
$use = valueMean('AB02');
if ($type < 1.5) {
text('typeA');
} elseif ($type <= 4.5) {
text('typeB');
} else {
text('typeC');
}
if ($use < 2.0) {
text('useA');
} elseif ($use < 4.0) {
text('useB');
} else {
text('useC');
}
?>
You will need to define a "value" function.
<?php
//Define it anywhere within the <?php tag
function value($arg){
// Your code logic here
}
I'm writing a PHP script for available rooms in a hotel. I want every combination for a group (i.e. 4 person). This is my array.
$room_array = array(
array(
"title" => "1 person room",
"room_for" => 1,
"price" => 79
),
array(
"title" => "2 person room with other",
"room_for" => 1,
"price" => 69
),
array(
"title" => "2 person room alone",
"room_for" => 1,
"price" => 89
),
array(
"title" => "2 person",
"room_for" => 2,
"price" => 69
),
array(
"title" => "3 person",
"room_for" => 3,
"price" => 69
)
);
Possible outcome:
4x 1 person room
4x 2 person room with other
3x 1 person room + 1x 2 person room with other
2x 2 person room
1x 3 person room + 1x 1 person room
etc. etc.
This calls for a recursive function. But every example I looked at doesn't work with counting in the inner array. The closest i found was this question:
Finding potential combinations of numbers for a sum (given a number set to select from)
But i didn't get de solution to work..
UPDATE:
Hi, thanks for all the answers. Really helped me in finding the best practice. In the meantime, the assignment has changed a little so I can't answer my own original question. My problem is solved. Thanks again for the help!
My answer below will get you partway there.
Resources
I borrowed some code logic from this answer.
To quote the answer (in case of future removal), please view below.
You can try
echo "<pre>";
$sum = 12 ; //SUM
$array = array(6,1,3,11,2,5,12);
$list = array();
# Extract All Unique Conbinations
extractList($array, $list);
#Filter By SUM = $sum $list =
array_filter($list,function($var) use ($sum) { return(array_sum($var) == $sum);});
#Return Output
var_dump($list);
Output
array
0 => array
1 => string '1' (length=1)
2 => string '2' (length=1)
3 => string '3' (length=1)
4 => string '6' (length=1)
1 => array
1 => string '1' (length=1)
2 => string '5' (length=1)
3 => string '6' (length=1)
2 => array
1 => string '1' (length=1)
2 => string '11' (length=2)
3 => array
1 => string '12' (length=2)
Functions Used
function extractList($array, &$list, $temp = array()) {
if(count($temp) > 0 && ! in_array($temp, $list))
$list[] = $temp;
for($i = 0; $i < sizeof($array); $i ++) {
$copy = $array;
$elem = array_splice($copy, $i, 1);
if (sizeof($copy) > 0) {
$add = array_merge($temp, array($elem[0]));
sort($add);
extractList($copy, $list, $add);
} else {
$add = array_merge($temp, array($elem[0]));
sort($add);
if (! in_array($temp, $list)) {
$list[] = $add;
}
}
}
}
My answer
The code below uses the code referenced above. I changed the return functionality of the array_filter function to map it to your needs.
The only thing left for you to do is change the function so that it can catch multiple of the same type of room. At the moment, the code below will only output 1 of each type of room (as per the code referenced above). An easy way to get around this would be to multiply the array values you send to the function by the number of guests you are searching for rooms, but up to the amount of rooms available. So: if you are looking to book for 4 guests and you have no single rooms remaining and only 1 double room, your best match result would have to be a 2 person room and a 3 person room. I've added some brief functionality to add this (it's commented out), although I have not tested it. It will likely take a while to process that as well so if you're looking for a quicker method, you're gonna have to use a better algorithm as already mentioned in previous comments/answers or solve P vs NP
The code below also gives you the option to toggle a value of $exact. This value, if set to true, will return only matches exactly equal to the number of guests, and if set to false will return all matches that equal to at least the number of guests.
<?php
class Booking {
private $minGuests = 1;
protected $guests = 1;
protected $rooms = [];
public function getRoomCombinations(bool $exact = true) {
$guests = $this->guests;
$list = [];
$rooms = $this->rooms;
/*for($i = 0; $i < $guests-1; $i++) {
$rooms = array_merge($rooms, $this->rooms);
}
asort($rooms);*/
$this->extractList($rooms, $list);
$result = array_filter($list, function($var) use ($guests, $exact) {
if($exact)
return(array_sum(array_map(function($item) { return $item['room_for'];}, $var)) == $guests);
else
return(array_sum(array_map(function($item) { return $item['room_for'];}, $var)) >= $guests && count($var) <= $guests);
});
array_multisort(array_map('count', $result), SORT_ASC, $result);
return $result;
}
private function extractList(array $array, array &$list, array $temp = []) {
if (count($temp) > 0 && !in_array($temp, $list))
$list[] = $temp;
for($i = 0; $i < sizeof($array); $i++) {
$copy = $array;
$elem = array_splice($copy, $i, 1);
if (sizeof($copy) > 0) {
$add = array_merge($temp, array($elem[0]));
sort($add);
$this->extractList($copy, $list, $add);
} else {
$add = array_merge($temp, array($elem[0]));
sort($add);
if (!in_array($temp, $list)) {
$list[] = $add;
}
}
}
}
public function setGuests(int $guests) {
$this->guests = ($guests >= $this->minGuests ? $guests : $this->minGuests);
return $this;
}
public function setHotelRooms(array $rooms) {
$this->rooms = $rooms;
return $this;
}
}
$booking = (new Booking())
->setGuests(4)
->setHotelRooms([
[
"title" => "1 person room",
"room_for" => 1,
"price" => 79
],
[
"title" => "2 person room with other",
"room_for" => 1,
"price" => 69
],
[
"title" => "2 person room alone",
"room_for" => 1,
"price" => 89
],
[
"title" => "2 person",
"room_for" => 2,
"price" => 69
],
[
"title" => "3 person",
"room_for" => 3,
"price" => 69
]
]);
echo '<pre>' . var_export($booking->getRoomCombinations(true), true) . '</pre>';
?>
If you need all the combinations then you can use an backtracking iterative algorithm (depth path).
In summary:
Type of tree: binary tree because all the levels can contain a solution when the number of persons contabilized = objetive
Binary tree
Algorithm functions
You need to increment the cont every time that a level is generated with the number of persons of the level and decrement when you change your track (exploring brothers or back)
solution: array[0..levels-1] values {0 (node not selected) ,1 (node selected)}
solution[0] = 1 -> You choose that "1 person room" belongs to the solution
solutions: list/array of objects and every object contains array of titles of rooms
function Backtracking ()
level:= 1
solution:= s_initial
end:= false
repeat
generate(level, solution)
IF solution(level, solution) then
save_solution
else if test(level, solution) then
level:= level+ 1
else
while NOT MoreBrothers(level, solution)
go_back(level, s)
until level==0
2.1. Generate: generate next node
2.2. Solution: test if it's a solution
2.3. Critery: if we must continue by this track or bound
2.4. MoreBrothers: if there are nodes without check at this level
2.5. Backtrack: all the nodes at this level were explored
2.6. Save solution: add to the solutions array your object that contains strings
$room_array = array(
array(
"title" => "1 person room",
"room_for" => 1,
"price" => 79
),
array(
"title" => "2 person room with other",
"room_for" => 1,
"price" => 69
),
array(
"title" => "2 person room alone",
"room_for" => 1,
"price" => 89
),
array(
"title" => "2 person",
"room_for" => 2,
"price" => 69
),
array(
"title" => "3 person",
"room_for" => 3,
"price" => 69
)
);
// Gets rooms based on a given number of guests
function get_possible_rooms($num_guests) {
global $room_array;
$possible_rooms = [];
foreach ($room_array as $room) {
if ($num_guests <= $room['room_for']) {
$possible_rooms[] = $room['title'];
}
}
return $possible_rooms;
}
// Gets the available room capacities
function get_room_capacities() {
global $room_array;
$capacities = [];
foreach ($room_array as $room) {
$capacities[] = $room['room_for'];
}
return array_unique($capacities);
}
// Gets the different combinations of groups of guests based on the room capacities
function get_guest_assignments($remaining_guests, $parent_id = '', $num_guests, &$result) {
$room_capacities = get_room_capacities();
for ($i = 1; $i <= $remaining_guests; ++$i) {
if (in_array($i, $room_capacities)) {
$parent_guests = (isset($result[$parent_id])) ? $result[$parent_id] : 0;
$result[$parent_id . $i] = $parent_guests + $i;
for ($j = 1; $j <= $remaining_guests - $i; ++$j) {
// Recursively get the results for children
get_guest_assignments($j, $parent_id . $i, $num_guests, $result);
}
}
}
if ($remaining_guests === 1 && $parent_id !== '') {
// If it reaches the end and it does not fulfill the required number of guests,
// mark it for removal later
if ($result[$parent_id] < $num_guests) {
$result[$parent_id] = null;
}
}
// This is the last recursion
if ($result[$parent_id . '1'] === $num_guests) {
// Remove duplicates.
// To do this, we need to re-sort the keys (e.g. 21 becomes 12) and call array_unique()
// I admit this is a bit sloppy implementation.
$combinations = [];
foreach ($result as $key => $value) {
if ($value !== null) {
$nums = str_split($key);
sort($nums);
$combinations[] = implode('', $nums);
}
}
$result = array_unique($combinations);
}
}
// Gets the rooms for each group of guest
function get_room_assignments($guest_str) {
$rooms = [];
for ($i = 0; $i < strlen($guest_str); ++$i) {
$num_guests = intval(substr($guest_str, $i, 1));
$rooms[] = get_possible_rooms($num_guests);
}
return $rooms;
}
//----------
// RUN
//----------
$guests = 4;
$result = [];
get_guest_assignments($guests, null, $guests, $result);
foreach ($result as $guest_combi) {
$assignments = get_room_assignments($guest_combi);
// Printing output
echo 'Guest Combination ' . $guest_combi . "\n";
echo json_encode($assignments, JSON_PRETTY_PRINT);
echo "\n\n";
}
The output will look something like this:
...
Guest Combination 13
[
[
"1 person room",
"2 person room with other",
"2 person room alone",
"2 person",
"3 person"
],
[
"3 person"
]
]
...
"Guest combination 13" means the 4 guests will be split into groups of 1 and 3 persons.
Output is an array of possible rooms for each group. So in the example, the group of 1 can book 1 person room, 2 person room with other, ... 3 person room. And the group of 3 can book 3 person room.
—
Other notes:
I know we hate global but doing this just for brevity. Feel free to modify.
There's a shorter way to code this, but this implementation makes it easier to debug since guest combinations are used as keys.
I have this loop, which shows books based in a year:
foreach ($cases_result as $case) {
$i = $case->n_ano;
switch ($i) {
case $i >= 2013:
echo $case->book.'<br>';
break;
case $i <= 2012 && $i >= 2011:
echo $case->book.'<br>';
break;
case $i <= 2010 && $i >= 2009:
echo $case->book.'<br>';
break;
case $i <= 2008 && $i >= 2007:
echo $case->book.'<br>';
break;
}
}
Is possible to to add a non-repeatable line to separate each case?
I need to show the year, like so:
2013
- book 1
- book 2
2012
- book 3
- book 4
Here is an excerpt of the array:
array (size=22)
0 =>
object(stdClass)[14]
public 'book' => string 'book 1' (length=6)
public 'n_ano' => string '2013' (length=4)
1 =>
object(stdClass)[15]
public 'book' => string 'book 2' (length=6)
public 'n_ano' => string '2013' (length=4)
2 =>
object(stdClass)[16]
public 'book' => string 'book 3' (length=6)
public 'n_ano' => string '2012' (length=4)
This should work for you:
First I create an array, which uses the year as key and adds the book name to the array, so you then can simply loop over it, e.g.
<?php
foreach($arr as $v)
$data[$v->n_ano][] = $v->book;
foreach($data as $n_ano => $books) {
echo $n_ano . "<br>";
foreach($books as $book)
echo " - " . $book . "<br>";
}
?>
output:
2013
- book 1
- book 2
2012
- book 3
First, sort your array by n_ano. Then you can easily loop trough the sorted result and create a grouped output.
function sortCases($a, $b) {
return $a->n_ano < $b->n_ano;
}
usort($cases_result, "sortCases");
$out = '';
$i = 0;
foreach ($cases_result as $case) {
//If the year is different, print year and assign it so $i
if($i !== intval($case->n_ano)) {
$out .= '<h2>' . $case->n_ano . '</h2>';
$i = intval($case->n_ano);
}
$out .= $case->book . '<br>';
}
print $out;
I would like to display some array data in relation to a competition, each player is ranked by the number of points they have, however if a player has the same amount of points to somebody else they should both have the exact same ranking position.
For instance...
1st Bob 500pts
2nd Joe 350pts
3rd Tom 250pts
3rd Tim 250pts
5th Jay 100pts
In this instance, as Tom & Tim have the exact same number of points they should be joint third, making the next person down 5th (rather than 4th), can anyone suggest the best way to achieve this with a simple array similar to follows
array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
Can anyone suggest the 'cleanest' solution for achieving this
This code will work for you:
$array = array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
arsort($array, SORT_NUMERIC);
$previousPoints = null;
$position = $total = 1;
foreach($array as $name=>$points) {
if ($points != $previousPoints) {
$position = $total;
}
echo $position.' '.$name.' '.$points."\n";
$previousPoints = $points;
$total++;
}
Online demo here.
$ar = array(
'Bob' => 500,
'Tim' => '250',
'Joe' => '350',
'Tom' => '250',
'Jay' => '100'
);
arsort($ar, SORT_NUMERIC);
$i = 1;
$previous = 1;
$previousPosition = 1;
foreach($ar as $k => $v)
{
if($v === $previous)
{
//If the value now is the same as the previous value use the previous position
echo "Position: $previousPosition, $k : $v <br />";
}
else
{
echo "Position: $i, $k : $v <br />";
}
//Previous value
$previous = $v;
//Previous Position
$previousPosition = $i;
//Always increment the value
$i++;
}
Try below code:
$a = array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
arsort($a);
$rank = 1;
$index = 1;
$prevUserPoints = 0;
foreach($a as $name=>$points) {
if($points != $prevUserPoints) {
$rank = $index;
}
$index++;
echo $rank . ' ' . $name . ' ' . $points . "\n";
$prevUserPoints = $points;
}
For displaying 1 as 1st, 2 as 2nd etc, you can use something like below:
function ordSuffix($n) {
$str = "$n";
$t = $n > 9 ? substr($str,-2,1) : 0;
$u = substr($str,-1);
if ($t==1) return $str . 'th';
else switch ($u) {
case 1: return $str . 'st';
case 2: return $str . 'nd';
case 3: return $str . 'rd';
default: return $str . 'th';
}
}
example: echo ordSuffix(23); This prints 23rd
Just a basic and alternative point of view you might want to consider.
$arr = [
"Joe" => "350",
"Tom" => "250",
"Jay" => "200",
"Tim" => "250",
"Bob" => "500",
"John" => "250" ,
"Paul" => "251.40"
];
$rank = array();
array_walk($arr,function($v, $k) use (&$rank)
{
if(isset($rank[$v]))
{
$rank[$v][$k] = $v;
asort($rank[$v]); //alphabetical order John, Tim, Tom
} else
{
$rank[$v] = array($k => $v);
}
});
krsort($rank);
var_dump(array_values($rank));
Let's say I have an array like this :
$intarray = array("300","350","399","650","625","738","983","1200","1050");
how can I display this array to user like this :
Price
_________________
[] 300 - 699 (5)
[] 700 - 999 (2)
[] 1000 - 1500 (2)
Details :
as in the example I wanted to show the user not the whole elements but option to select between them by giving limits low and max limits. So if user select 300 - 699, page display the results between 300-699
That $intarray is generated dynamically so some code must handle the splitting. Array can
have more elements. What I want is divide the numbers like 5 range options to show the user.
Having in mind my comment, I assume you want to count particular ranges.
<?php
$intarray = array("300","350","399","650","625","738","983","1200","1050");
//echo "[] ". $intarray[0]. " - " .$intarray[4][0]."99"; # that was in my comment
$ranges = array(
0 => array(
'min' => 300,
'max' => 699
),
1 => array(
'min' => 700,
'max' => 999
),
2 => array(
'min' => 1000,
'max' => 1500
)
);
foreach ($intarray as $val) {
for ($i = 0; $i < count($ranges); $i++){
if ($val >= $ranges[$i]['min'] && $val <= $ranges[$i]['max']) {
$range_values[$i][] = $val;
}
}
}
var_dump($range_values);
array (size=3)
0 =>
array (size=5)
0 => string '300' (length=3)
1 => string '350' (length=3)
2 => string '399' (length=3)
3 => string '650' (length=3)
4 => string '625' (length=3)
1 =>
array (size=2)
0 => string '738' (length=3)
1 => string '983' (length=3)
2 =>
array (size=2)
0 => string '1200' (length=4)
1 => string '1050' (length=4)
You can use count() in order to display the thing in the brackets
for ($i = 0; $i < count($ranges); $i++) {
$max = max($range_values[$i]);
echo "[] " . min($range_values[$i]) . " - " . $max[0]."99" . " (". count($range_values[$i]).")" . "<br />";
}
[] 300 - 699 (5)
[] 738 - 999 (2)
[] 1050 - 199 (2)
Or just display the ranges (as it was the desired output?) and count($ranges_values) current iteration
for ($i = 0; $i < count($ranges); $i++) {
echo "[] " . $ranges[$i]['min'] . " - " . $ranges[$i]['max'] . " (" . count($range_values[$i]) . ")" . "<br />";
}
[] 300 - 699 (5)
[] 700 - 999 (2)
[] 1000 - 1500 (2)
Try
$intarray = array("300","350","399","650","625","738","983","1200","1050");
sort($intarray);
$result=array();
foreach($intarray as $key=>$val){
switch($val){
case ($val > 300 && $val < 699):
$result[0][] = $val;
break;
case ($val > 700 && $val < 999):
$result[1][] = $val;
break;
case ($val > 1000 && $val < 1500):
$result[2][] = $val;
break;
}
}
demo here
You can do a function that prints and counts the numbers in your range
public function printInRanges($startRange, $endRange)
{
$count = 0;
foreach($element in $array)
{
if($element>=$startRange && $element<=$endRange)
count++;
}
echo $startRange."-".$endRange."(".$count.")";
}
And than you can call this function with whatever ranges you want
Last Edit
if you want to do this for all your array, get your first element value (array[0]) and last element value, and call the function from a loop
$startValue = array[0];
while($startValue + 500 < $endValue)// 500 being the value between ranges like 0-500,500-1000,1000-1500
{
printInRanges($startValue ,$startValue +500);
$startValue+=500;
}