Convert my script in recursive way? - php

I have script who searches closest searched number.
So for example, let say that in array are this numbers:
'0' => 1.72
'0.25' => 1.92
'0.75'=> 2.35
'1' => 3.00
I am searching for 0.50 handicap, so 0.25 and 0.75 are in same range from 0.50.
In this situations i want to get greater number, what is 0.75 in this example.
Code what works is this:
function getClosest($search, $arr) {
$closest = null;
$num_arr = array();
$odd = 0.00;
$i = 0;
foreach ($arr as $handicap=>$item) { //first closest number
if ($closest === null || abs($search - $closest) > abs($handicap - $search)) {
$closest = $handicap;
$odd = $item;
}
else{
$num_arr[$handicap] = $item;
}
}
$newclosest = null;
$newodd = 0.00;
foreach($num_arr as $handicap=>$newitem){ //second closest number
if ($newclosest === null || abs($search - $closest) > abs($handicap - $search)) {
$newclosest = $handicap;
$newodd = $newitem;
}
}
//if difference between first and second number are same
if(abs($search - $closest) == abs($newclosest - $search)){
if($newclosest > $closest){ //if second number is greater than first
$closest = $newclosest;
$odd = $newodd;
}
}
return array('handicap'=>$closest,'odd'=>$odd);
}
I see that i can use recursion here, but i am not experienced in using recursion. I know that i need call it inside like this:
$rec_arr = getClosest($num_arr,$search);
but i get blank page even i dump function output.

use array_map function,
$data = array('0'=>1.72,'0.75'=> 2.35,'0.25'=>1.92,'1' => 3.00);
$v = 0.5; // search value
$x = null; // difference value
$y = array(); // temporary array
array_map(function($i)use($data,$v,&$x,&$y){
if(isset($x)){
if($x > abs($i-$v)){ // if difference value is bigger than current
$x = abs($i-$v);
$y = array($i=>$data[$i]);
}else if($x == abs($i-$v)){ // if difference value is same
$key = array_keys($y);
$y = $key[0] < $i ? array($i=>$data[$i]) : $y;
}
}else{ // first loop
$x = abs($i-$v);
$y = array($i=>$data[$i]);
}
},array_keys($data));
print_r($y); // result
output Array ( [0.75] => 2.35 ), hope this help you.

//$a is array to be searched
//$s is search key
//$prev_key and $next_key will be output required
$a = array('0'=>1,'0.25'=>123,'0.75'=>456,'0.78'=>456,'1'=>788);
$s = '0';
if(isset($a[$s])){
echo $s;
}
else{
reset($a);//good to do
while(key($a) < $s){
next($a);
}
$next_key = key($a);
prev($a);
$prev_key = key($a);
echo $prev_key.'-'.$next_key;
}
The above code uses array internal pointers. I think this may help you..
source: https://stackoverflow.com/a/4792770/3202287

Related

Get nearest sequence result from an array and given pattern with PHP

I am trying to get year and month from the letters using established sequence. I know that the sequence is based on the following letters:
$letters = array('B','C','D','F','G','H','J','K','L','M','N','P','R','S','T','V','W','X','Y','Z');
It started with 0000BBB and when it reaches 9999 it becomes BBC, BBD etc. So I don't need the numbers in that case and only letters as I have a list of last registered sequence per year and month like this:
$plates = array(
array('2018','KHF','KHX','KJV','KKN','KLM','KML','KNK','KPD','KPR','KPT','----','----'),
array('2017','JWN','JXF','JYB','JYT','JZP','KBM','KCH','KCV','KDK','KFB','KFV','KGN'),
array('2016','JLN','JMF','JMY','JNR','JPK','JRG','JRZ','JSL','JTB','JTR','JVH','JVZ'),
array('2015','JCK','JCY','JDR','JFG','JFW','JGP','JHJ','JHT','JJH','JJW','JKK','JKZ'),
array('2014','HVN','HVZ','HWM','HXB','HXN','HYD','HTY','HZB','HZL','HZZ','JBL','JBY'),
array('2013','HNT','HPC','HPN','HPY','HRK','HRX','HSK','HSR','HSZ','HTK','HTV','HVF'),
array('2012','HJC','HJM','HKB','HKL','HKX','HLK','HLW','HMD','HML','HMT','HNC','HNK'),
array('2011','HBP','HCB','HCR','HDC','HDR','HFF','HFT','HGC','HGM','HGX','HHH','HHT'),
array('2010','GTC','GTS','GVM','GWC','GWV','GXP','GYD','GYM','GYX','GZJ','GZT','HBG'),
array('2009','GKS','GLC','GLP','GMC','GMN','GNF','GNY','GPJ','GPW','GRM','GSC','GSR'),
array('2008','FZR','GBN','GCK','GDH','GFC','GFY','GGV','GHG','GHT','GJJ','GJV','GKH'),
array('2007','FKY','FLV','FNB','FNZ','FRC','FSJ','FTP','FVJ','FWC','FXB','FXY','FYY'),
array('2006','DVW','DWT','DXZ','DYY','FBC','FCJ','FDP','FFK','FGF','FHD','FJD','FKC'),
array('2005','DFZ','DGX','DHZ','DKB','DLD','DMJ','DNP','DPK','DRG','DSC','DTB','DVB'),
array('2004','CRV','CSS','CTT','CVR','CWR','CXT','CYY','CZP','DBJ','DCH','DDG','DFF'),
array('2003','CDV','CFM','CGJ','CHF','CJC','CKB','CLD','CLV','CMM','CNK','CPF','CRC'),
array('2002','BSL','BTF','BTZ','BVW','BWT','BXP','BYP','BZF','BZV','CBP','CCH','CDC'),
array('2001','BFJ','BGF','BHG','BJC','BKB','BLC','BMF','BMW','BNL','BPG','BRB','BRT'),
array('2000','---','---','---','---','---','---','---','---','BBJ','BCD','BCY','BDR')
);
That means that array index 0 is the year and from 1 to 12 would be month. I am trying to find a match but then realize I can not search exact value and need to look for nearest value based on letters.
I would deeply appreciate if anyone could direct me in right direction what would be the best method of doing this.
This is a test so far but this will just return an exact match, I would have to search any possible letters such as KHW as an example that would have to match as nearest value to KHX
foreach ($plates as $key => $val) {
$search = array_search('KHX', $plates[$key]);
if($search){
echo $search."\n";
echo $plates[$key][0];
break;
}
}
You can solve it with O(log n) with a binary search. But in a more straightforward solution, you can solve it with O(n).
You can calculate the difference between each word with the below algorithm.
‍‍
<?php
function strToInt($str)
{
$result = 0;
for ($i = 0; $i < strlen($str); $i++) {
$result = $result * 100 + ord($str[$i]);
}
return $result;
}
function find($searchStr)
{
$plates = [
['2018','KHF','KHX','KJV','KKN','KLM','KML','KNK','KPD','KPR','KPT','----','----'],
['2017','JWN','JXF','JYB','JYT','JZP','KBM','KCH','KCV','KDK','KFB','KFV','KGN'],
['2016','JLN','JMF','JMY','JNR','JPK','JRG','JRZ','JSL','JTB','JTR','JVH','JVZ'],
['2015','JCK','JCY','JDR','JFG','JFW','JGP','JHJ','JHT','JJH','JJW','JKK','JKZ'],
['2014','HVN','HVZ','HWM','HXB','HXN','HYD','HTY','HZB','HZL','HZZ','JBL','JBY'],
['2013','HNT','HPC','HPN','HPY','HRK','HRX','HSK','HSR','HSZ','HTK','HTV','HVF'],
['2012','HJC','HJM','HKB','HKL','HKX','HLK','HLW','HMD','HML','HMT','HNC','HNK'],
['2011','HBP','HCB','HCR','HDC','HDR','HFF','HFT','HGC','HGM','HGX','HHH','HHT'],
['2010','GTC','GTS','GVM','GWC','GWV','GXP','GYD','GYM','GYX','GZJ','GZT','HBG'],
['2009','GKS','GLC','GLP','GMC','GMN','GNF','GNY','GPJ','GPW','GRM','GSC','GSR'],
['2008','FZR','GBN','GCK','GDH','GFC','GFY','GGV','GHG','GHT','GJJ','GJV','GKH'],
['2007','FKY','FLV','FNB','FNZ','FRC','FSJ','FTP','FVJ','FWC','FXB','FXY','FYY'],
['2006','DVW','DWT','DXZ','DYY','FBC','FCJ','FDP','FFK','FGF','FHD','FJD','FKC'],
['2005','DFZ','DGX','DHZ','DKB','DLD','DMJ','DNP','DPK','DRG','DSC','DTB','DVB'],
['2004','CRV','CSS','CTT','CVR','CWR','CXT','CYY','CZP','DBJ','DCH','DDG','DFF'],
['2003','CDV','CFM','CGJ','CHF','CJC','CKB','CLD','CLV','CMM','CNK','CPF','CRC'],
['2002','BSL','BTF','BTZ','BVW','BWT','BXP','BYP','BZF','BZV','CBP','CCH','CDC'],
['2001','BFJ','BGF','BHG','BJC','BKB','BLC','BMF','BMW','BNL','BPG','BRB','BRT'],
['2000','---','---','---','---','---','---','---','---','BBJ','BCD','BCY','BDR']
];
$minYear = null;
$minKey = null;
$minDiff = strToInt('ZZZ');
$searchInt = strToInt($searchStr);
for ($i = 0; $i < count($plates); $i++) {
for ($j = 1; $j < 13; $j++) {
if(abs($searchInt - strToInt($plates[$i][$j])) < $minDiff) {
$minDiff = abs($searchInt - strToInt($plates[$i][$j]));
$minYear = $plates[$i][0];
$minKey = $plates[$i][$j];
}
}
}
return [$minYear, $minKey];
}
print_r(find('KHW'));
The code down below is by no means optimized, but it's rather a concept of how you might solve your problem.
//Flatten out array (one dimension without years and ----)
$flatten = array();
foreach($plates as $platevalues) {
foreach($platevalues as $pv) {
if ($pv != '---' && $pv != '----' && intval($pv) == 0) {
//Create a string only if valid letters included in the $letters-array
//This string is then added to the new array that is flattened out
$pv2 = '';
for($i=0;$i<strlen($pv);$i++) {
$letter = substr($pv,$i,1);
if (in_array($letter, $letters) !== false) {
$pv2 .= $letter;
}
}
$flatten[] = $pv2;
}
}
}
//Do the search
$search = 'GWN';
$search_result = '';
//Create a new search string based on first found in flattened
//plates array (first G, then GW, then GWN)
for($i=0;$i<strlen($search);$i++) {
foreach($flatten as $key=>$f) {
if (substr($search,0,$i+1) == substr($f,0,$i+1)) {
$search_result .= substr($search,$i,1);
break;
}
}
}
/*
$search_result is: GW
*/
//Create a new array where all items that begins with GW are included
$result = [];
foreach($flatten as $key=>$item) {
if (substr($search_result,0,strlen($search_result)) ==
substr($item,0,strlen($search_result))) {
$result[] = $item;
}
}
/*
$result =
array (size=2)
0 => string 'GWC' (length=3)
1 => string 'GWV' (length=3)
*/
//Create an array with total ASCII-value for each item
//in the $result array above
$result_o = [];
foreach($result as $item) {
$o = 0;
for($i=0;$i<strlen($item);$i++) {
$o += ord(substr($item,$i,1));
}
$result_o[]= $o;
}
/*
$result_o =
array (size=2)
0 => int 225
1 => int 244
*/
//Get the total ASCII-value for the original search string
$search_o = 0;
for($i=0;$i<strlen($search);$i++) {
$search_o += ord(substr($search,$i,1));
}
/*
$search_ o = 236
*/
//Find closest value in the $result_o (ASCII) - array compared (225,244)
//to the original $search_o ASCII value above (236)
$closest = 0;
$use_key = 0;
foreach($result_o as $key=>$item) {
if ($closest == 0 || abs($search_o - $closest) > abs($item - $search_o)) {
$closest = $item;
$use_key = $key;
}
}
/*
$closest = 244 (it's closer to 236 than 225 is)
$use_key = 1
*/
To get the result you have:
/*
$result =
array (size=2)
0 => string 'GWC' (length=3)
1 => string 'GWV' (length=3)
*/
//This should print out GWV
echo 'result=' . $result[$use_key];

Get lowest price on sum of combinations in given array

This code is working fine when the array length is 8 or 10 only. When we are checking this same code for more than 10 array length.it get loading not showing the results.
How do reduce my code. If you have algorithm please share. Please help me.
This program working flow:
$allowed_per_room_accommodation =[2,3,6,5,3,5,2,5,4];
$allowed_per_room_price =[10,30,60,40,30,50,20,60,80];
$search_accommodation = 10;
i am get subsets = [5,5],[5,3,2],[6,4],[6,2,2],[5,2,3],[3,2,5]
Show lowest price room and then equal of 10 accommodation; output like as [5,3,2];
<?php
$dp=array(array());
$GLOBALS['final']=[];
$GLOBALS['room_key']=[];
function display($v,$room_key)
{
$GLOBALS['final'][] = $v;
$GLOBALS['room_key'][] = $room_key;
}
function printSubsetsRec($arr, $i, $sum, $p,$dp,$room_key='')
{
// If we reached end and sum is non-zero. We print
// p[] only if arr[0] is equal to sun OR dp[0][sum]
// is true.
if ($i == 0 && $sum != 0 && $dp[0][$sum]) {
array_push($p,$arr[$i]);
array_push($room_key,$i);
display($p,$room_key);
return $p;
}
// If $sum becomes 0
if ($i == 0 && $sum == 0) {
display($p,$room_key);
return $p;
}
// If given sum can be achieved after ignoring
// current element.
if (isset($dp[$i-1][$sum])) {
// Create a new vector to store path
// if(!is_array(#$b))
// $b = array();
$b = $p;
printSubsetsRec($arr, $i-1, $sum, $b,$dp,$room_key);
}
// If given $sum can be achieved after considering
// current element.
if ($sum >= $arr[$i] && isset($dp[$i-1][$sum-$arr[$i]]))
{
if(!is_array($p))
$p = array();
if(!is_array($room_key))
$room_key = array();
array_push($p,$arr[$i]);
array_push($room_key,$i);
printSubsetsRec($arr, $i-1, $sum-$arr[$i], $p,$dp,$room_key);
}
}
// Prints all subsets of arr[0..n-1] with sum 0.
function printAllSubsets($arr, $n, $sum,$get=[])
{
if ($n == 0 || $sum < 0)
return;
// Sum 0 can always be achieved with 0 elements
// $dp = new bool*[$n];
$dp = array();
for ($i=0; $i<$n; ++$i)
{
// $dp[$i][$sum + 1]=true;
$dp[$i][0] = true;
}
// Sum arr[0] can be achieved with single element
if ($arr[0] <= $sum)
$dp[0][$arr[0]] = true;
// Fill rest of the entries in dp[][]
for ($i = 1; $i < $n; ++$i) {
for ($j = 0; $j < $sum + 1; ++$j) {
// echo $i.'d'.$j.'.ds';
$dp[$i][$j] = ($arr[$i] <= $j) ? (isset($dp[$i-1][$j])?$dp[$i-1][$j]:false) | (isset($dp[$i-1][$j-$arr[$i]])?($dp[$i-1][$j-$arr[$i]]):false) : (isset($dp[$i - 1][$j])?($dp[$i - 1][$j]):false);
}
}
if (isset($dp[$n-1][$sum]) == false) {
return "There are no subsets with";
}
$p;
printSubsetsRec($arr, $n-1, $sum, $p='',$dp);
}
$blockSize = array('2','3','6','5','3','5','2','5','4');
$blockvalue = array('10','30','60','40','30','50','20','60','80');
$blockname = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese");
$processSize = 10;
$m = count($blockSize);
$n = count($processSize);
// sum of sets in array
printAllSubsets($blockSize, $m, $processSize);
$final_subset_room = '';
$final_set_room_keys = '';
$final_set_room =[];
if($GLOBALS['room_key']){
foreach ($GLOBALS['room_key'] as $set_rooms_key => $set_rooms) {
$tot = 0;
foreach ($set_rooms as $set_rooms) {
$tot += $blockvalue[$set_rooms];
}
$final_set_room[$set_rooms_key] = $tot;
}
asort($final_set_room);
$final_set_room_first_key = key($final_set_room);
$final_all_room['set_room_keys'] = $GLOBALS['room_key'][$final_set_room_first_key];
$final_all_room_price['set_room_price'] = $final_set_room[$final_set_room_first_key];
}
if(isset($final_all_room_price)){
asort($final_all_room_price);
$final_all_room_first_key = key($final_all_room_price);
foreach ($final_all_room['set_room_keys'] as $key_room) {
echo $blockname[$key_room].'---'. $blockvalue[$key_room];
echo '<br>';
}
}
else
echo 'No Results';
?>
I'm assuming your task is, given a list rooms, each with the amount of people it can accommodate and the price, to accommodate 10 people (or any other quantity).
This problem is similar to 0-1 knapsack problem which is solvable in polynomial time. In knapsack problem one aims to maximize the price, here we aim to minimize it. Another thing that is different from classic knapsack problem is that full room cost is charged even if the room is not completely occupied. It may reduce the effectiveness of the algorithm proposed at Wikipedia. Anyway, the implementation isn't going to be straightforward if you have never worked with dynamic programming before.
If you want to know more, CLRS book on algorithms discusses dynamic programming in Chapter 15, and knapsack problem in Chapter 16. In the latter chapter they also prove that 0-1 knapsack problem doesn't have trivial greedy solution.

How to convert word to number using my function?

I created this function to converting numbers to words. And how I can convert words to number using this my function:
Simple function code:
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$n = "98"; // Input number to converting
if($n < 10 && $n > -1){
echo $array[$n];
}
if($n == 10 OR $n == 20 OR $n == 30 OR $n == 40 OR $n == 50 OR $n == 60 OR $n == 70 OR $n == 80 OR $n == 90 OR $n == 100){
echo $array[$n];
}
if(mb_strlen($n) == 2 && $n[1] != 0)
{
$d = $n[0]."0";
echo "$array[$d]У ".$array[$n[1]];
}
My function so far converts the number to one hundred. How can I now convert text to a number using the answer of my function?
So, as #WillParky93 assumed, your input has spaces between words.
<?php
mb_internal_encoding("UTF-8");//For testing purposes
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$postfixes = array("3" => "ВУ");
$n = "98"; // Input number to converting
$res = "";
//I also optimized your conversion of numbers to words
if($n > 0 && ($n < 10 || $n%10 == 0))
{
$res = $array[$n];
}
if($n > 10 && $n < 100 && $n%10 != 0)
{
$d = intval(($n/10));
$sd = $n%10;
$ending = isset($postfixes[$d]) ? $postfixes[$d] : "У";
$res = ($array[$d * 10]).$ending." ".$array[$sd];
}
echo $res;
echo "\n<br/>";
$splitted = explode(" ", $res);
//According to your example, you use only numerals that less than 100
//So, to simplify your task(btw, according to Google, the language is tajik
//and I don't know the rules of building numerals in this language)
if(sizeof($splitted) == 1) {
echo array_search($splitted[0], $array);
}
else if(sizeof($splitted) == 2) {
$first = $splitted[0];
$first_length = mb_strlen($first);
if(mb_substr($first, $first_length - 2) == "ВУ")
{
$first = mb_substr($first, 0, $first_length - 2);
}
else
{
$first = mb_substr($splitted[0], 0, $first_length - 1);
}
$second = $splitted[1];
echo (array_search($first, $array) + array_search($second, $array));
}
You didn't specify the input specs but I took the assumption you want it with a space between the words.
//get our input=>"522"
$input = "ПАНҶ САД БИСТ ДУ";
//split it up
$split = explode(" ", $input);
//start out output
$c = 0;
//set history
$history = "";
//loop the words
foreach($split as &$s){
$res = search($s);
//If number is 9 or less, we are going to check if it's with a number
//bigger than or equal to 100, if it is. We multiply them together
//else, we just add them.
if((($res = search($s)) <=9) ){
//get the next number in the array
$next = next($split);
//if the number is >100. set $nextres
if( ($nextres = search($next)) >= 100){
//I.E. $c = 5 * 100 = 500
$c = $nextres * $res;
//set the history so we skip over it next run
$history = $next;
}else{
//Single digit on its own
$c += $res;
}
}elseif($s != $history){
$c += $res;
}
}
//output the result
echo $c;
function search($s){
global $array;
if(!$res = array_search($s, $array)){
//grab the string length
$max = strlen($s);
//remove one character at a time until we find a match
for($i=0;$i<$max; $i++ ){
if($res = array_search(mb_substr($s, 0, -$i),$array)){
//stop the loop
$i = $max;
}
}
}
return $res;
}
Output is 522.

PHP: Sort array according to another array of different length

I have two arrays of different length:
$paths_table = array("TS-0007_a.jpg", "TS-0040_a.JPG", "TS-0040_b.JPG", "TS-0040_f.JPG", "TS-0041_a.JPG", "TS-0041_b.JPG");
$order_table = array("TS-0040","TS-0007","TS-0041");
and I want to sort the first one using the second so that the output will be the array
$final_table = array("TS-0040_a.JPG", "TS-0040_b.JPG", "TS-0040_f.JPG", "TS-0007_a.jpg", TS-0041_a.JPG", "TS-0041_b.JPG")
Assuming that I'm going to use
strpos($paths_table[$i], $order_table[$j]);
to check if the string of $order_table is included in any of the $paths_table.
How can I accomplish this?
Preprocess the array so that each item contains an index of its prefix (that is, turn 'TS-0007_a.jpg' into [1,'TS-0007_a.jpg']):
foreach($paths_table as &$v) {
foreach($order_table as $n => $o)
if(strpos($v, $o) === 0) {
$v = [$n, $v];
break;
}
}
sort the array:
sort($paths_table);
and remove indexes:
foreach($paths_table as &$v)
$v = $v[1];
The following piece of code can off course be optimized in several ways, but for the sake of clarity I didnt.
$paths_table = array("TS-0007_a.jpg", "TS-0040_a.JPG", "TS-0040_b.JPG", "TS-0040_f.JPG", "TS-0041_a.JPG", "TS-0041_b.JPG");
$order_table = array("TS-0040","TS-0007","TS-0041");
$sorter = new PrefixSorter($order_table);
$output = usort($paths_table, array($sorter, 'sort'));
var_dump($paths_table);
class PrefixSorter {
private $prefixes;
function __construct($prefixes) {
$this->prefixes = $prefixes;
}
function sort($path1, $path2) {
$prefix1 = -1;
$prefix2 = -1;
foreach($this->prefixes as $index=>$prefix) {
if (substr($path1, 0, strlen($prefix)) == $prefix) $prefix1 = $index;
if (substr($path2, 0, strlen($prefix)) == $prefix) $prefix2 = $index;
}
if (($prefix1 == -1 && $prefix2 == -1) || $prefix1 == $prefix2) {
return 0;
}
else if ($prefix1 == -1 || $prefix1 > $prefix2) {
return 1;
}
else if ($prefix2 == -1 || $prefix1 < $prefix2) {
return -1;
}
}
}
I made a few assumptions:
You want to sort on the prefixes given in order_table
Prefixes not given are put at the back unordered.
You can off course change the code to match on string containment instead of prefixing

Foreach & Arrays in PHP

I'm terribly confused on how I should be writing this function...it basically scores a test, and it WORKS for one user's values.
Let's say I want the values for the following user: $id = 2...this works! If $id = array(2,3,4,5) it doesn't work!
function get_score_a($id){
// Case 4
foreach($this->get_results_a($id,4)->row() as $key=>$a){
if ($a >= 2 && $a <= 4) {
$score_a += 2;
} else if ($a > 4 && $a < 8) {
$score_a += 3;
} else if ($a > 8) {
$score_a += floor($a - 8) * .5;
$score_a += 3;
}
};
return $score_a;
}
function get_results_a($id, $method) {
$select_cols = array(
1 => array('a_1','a_2','a_4'),
2 => array('a_6','a_8','a_11','a_12','a_14'),
3 => array('a_3','a_10'),
4 => array('a_5','a_7','a_9','a_13')
);
return $this->db->select($select_cols[$method])
->where_in('id', $id)
->get('be_survey');
}
This returns a score...however, if I run multiple ids...it just adds up all the numbers, I think...
Instead I need this to output separate scores for individual users...
May it be noted that I'm a total noob! So vivacious explanations are very much appreciated. :)
Edit
Please review my code...as I should have been more clear! Sorry!
I apologize! In summation, this selects the correct values from the table, based on
And yes, my eyes hurt too!
Edit
I am too hasty! This is a Codeigniter project!
Firstly, there is no row() for arrays.. just use foreach ($array as $key=>$value)
Secondly, inside the foreach loop $score_b is being incremented on each run with its previous value. So, your code is outputting the sum of all player scores.
use:
foreach(array(5,5,5,6,7,78,8,7,7,6,5) as $key=>$a){
if ($a >= 0 && $a <= .5) {
$score_b[$key] += 0;
} else if ($a > .5 && $a < 2) {
$score_b[$key] += 1;
}
else if ($a > 2 && $a < 4) {
$score_b[$key] += 2;
}
else if ($a > 4) {
$score_b[$key] += floor($a - 8) * .5;
$score_b[$key] += 2;
}
};
$score_b will now be an array of scores.
EDIT:
Add the following in your code:
$id = array(2,3,4,5);
function get_score_array($ids) {
foreach ($ids as $id) {
$scores[$id] = get_score_a($id);
}
return $scores;
}
$scores will now be an array of $id=>$score pairs.
Also, adjust the above code, as per your framework (which I guess you are using)
There is no such method called row() on array. In fact, an array isn't strictly an object, so it doesn't have methods.
So, first of all, get rid of the ->row() invocation.
Second, where are you pushing these scores onto an array? I don't see where that happens in your code. Initialize an empty array before the foreach loop, and push the $score_b variable onto the array at the end of the loop.
Set a $userID variable outside the foreach loop like this:
$userScores = array(
'bobby' = > array(5,5,5,6,7,78,8,7,7,6,5),
'sue' = > array(5,5,5,6,7,78,8,7,7,6,5),
'joe' = > array(5,5,5,6,7,78,8,7,7,6,5)
);
foreach($userScores as $name => $a){
$score_b[$name] = 0; //initialize
if ($a >= 0 && $a <= .5) {
$score_b[$name] += 0;
} else if ($a > .5 && $a < 2) {
$score_b[$name] += 1;
}
else if ($a > 2 && $a < 4) {
$score_b[$name] += 2;
}
else if ($a > 4) {
$score_b[$name] += floor($a - 8) * .5;
$score_b[$name] += 2;
}
};
your end result should be something like (I didn't do any actual math)
$score_b['bobby'][100]
$score_b['sue'][75]
$score_b['joe'[90]

Categories