Distribute array value in table column - php

I have three column having limit of certain percentage of total.i want to distribute an array of values to three columns in such a manner first check customer 1 then 2 then 3 and start from customer 3,2,1 and again from 1,2,3 etc. And also check each value not crossing column limit.Remaining array value should be distribute in column having large percentage assigned.
Array : $stone_doll_inner_arr = array(1=>'67212','37256','32909','29847','28529','27643','25356','25274','23604','23058','18581');
I tried like
Table
for($m=1;$m<=1;$m++){
for($n=1;$n<=count($stone_doll_inner_arr);$n++){
if ($n % 2 == 0) {
$asc_desc = 'asc';
}else{
$asc_desc = 'desc';
}
//Query
$sql_main_table = "select * from create_nemix_tbl where create_id = '".$getid."' order by percentage ".$asc_desc."";
$qry_main_table = $con->query($sql_main_table);
$num_main_table = $qry_main_table->num_rows;
if ($n % 2 == 0) {
$l = $num_main_table-1;
}else{
$l = 0;
}
while($row_main_table = $qry_main_table->fetch_array()){
$stone_doll_val = $stone_doll_arr[$m];
$stone_doll_val_perc = ($stone_doll_val * $row_main_table['percentage']) / 100;
$pre_existing = isset($customer[$l]) ? array_sum($customer[$l]) : 0;
$first_value = $pre_existing+$stone_doll_inner_arr[$n];
$var = 0;
if ($first_value <= $stone_doll_val_perc){
$customer[$l][] = $stone_doll_inner_arr[$n];
unset($stone_doll_inner_arr[$n]);
$var =1;
}
if($var == 1){
break;
}
}
if ($n % 2 == 0) {
$l--;
}else{
$l++;
}
}
}
echo "<pre>";
print_r($customer);
Table Structure and output of script i wanted

Related

Comparing results in Gravity Forms

I've created a questionnaire with three categories. Each possible answer in the questionnaire corresponds with one of the categories. I have three admin numeric fields where I add the number of answers selected from each category (fields 121, 122, 123). This part of the form is working. I'd like to compare the totals from these fields to see which is greatest and then return that result to a hidden field (field 126). So far my code is triggering a critical error when I submit the form.
add_filter("gform_pre_submission_9", "find_highest_percent");
function find_highest_percent ($vata, $pitta, $kapha, $form) {
$total = 0;
$vata = $_POST["input_121"] ;
$pitta = $_POST["input_122"] ;
$kapha = $_POST["input_123"] ;
$total = $vata + $pitta + $kapha;
$vata_percent = ($vata / $total) * 100;
$pitta_percent = ($pitta / $total) * 100;
$kapha_percent = ($kapha / $total) * 100;
if (abs($vata - $kapha) <= 10) {
$result = "Vata-Kapha";
} elseif (abs($vata - $pitta) <= 10) {
$result = "Vata-Pitta";
} elseif (abs($pitta - $kapha) <= 10) {
$result = "Pitta-Kapha";
} elseif (abs($vata - $pitta) <= 10 && abs($vata - $kapha) <= 10 && abs($pitta - $kapha) <= 10) {
$result = "Tri-Doshic";
} else {
if ($vata > $pitta && $vata > $kapha) {
$result = "Vata";
} elseif ($pitta > $vata && $pitta > $kapha) {
$result = "Pitta";
} else {
$result = "Kapha";
}
}
$_POST["input_126"] = $result;
}
I've tested by removing all calculations and simply returning the number 100 but this also triggers the error. Grateful for any suggestions.
Does it help to set the variables to integers?
$vata = (int)$_POST["input_121"] ;
$pitta = (int)$_POST["input_122"] ;
$kapha = (int)$_POST["input_123"] ;

How can I generate and validate random IDs using the Saudi ID format?

I need to generate random IDs that validate against the criteria for Saudi IDs shown in this question:
Saudi Iqama/National Identity number field validation
I've tried the following code:
$random_numbers = [];
while(count($random_numbers) < 1000000000){
do {
$random_number = mt_rand(1000000000,9000000000);
}
while (in_array($random_number, $random_numbers));{
$type = substr ( $random_number, 0, 1 );
if($type != 2 && $type != 1 ) break;
$sum = 0;
for( $i = 0 ; $i<10 ; $i++ ) {
if ( $i % 2 == 0){
$ZFOdd = str_pad ( ( substr($random_number, $i, 1) * 2 ), 2, "0", STR_PAD_LEFT );
$sum += substr ( $ZFOdd, 0, 1 ) + substr ( $ZFOdd, 1, 1 );
}else{
$sum += substr ( $random_number, $i, 1 );
}
}
return $sum%10 ? break : echo $random_number;
----------
echo "<br>";
$random_numbers[] = $random_number;}
}
Disclaimer: I'm not 100% sure on the validation required etc. for Saudi ID numbers and have only briefly looked at the answers supplied in the linked question
Okay, so, my understanding is that you need to generate a random id that:
Matches the pattern/format:
[12]\d{9}
Validates against the criteria show in the linked question:
Saudi Iqama/National Identity number field validation
To do this we need to create a couple of functions; one to generate IDs and one to validate the IDs against the given criteria.
Generate the ID
Simply generating an ID is simple enough. We can use the random_int function in PHP with a loop. If we enclose the code to generate the ID inside of a do...while... loop then we can execute the code and validate the ID repeatedly until we get a valid one.
function getRandomSaudiId() : int
{
do {
$saudiId = (string) random_int(1,2);
for($i = 0; $i < 9; $i++){
$saudiId .= random_int(0,9);
}
} while(validateSaudiId($saudiId) === false);
return (int) $saudiId;
}
Validate the ID
Note: we convert to string so that we can access the numbers based on their index.
function validateSaudiId(string $id) : bool
{
$sum = 0;
for($i = 0; $i < 9; $i++){
if( $i % 2 ){
// Even number
$sum += $id[$i];
}
else{
//Odd number
$increment = $id[$i] * 2;
while($increment > 9){
$increment = (string) $increment;
$increment = $increment[0] + $increment[1];
}
$sum += $increment;
}
}
$sum = (string) $sum;
return ($sum[1] == $id[9] || $id[9] == (10 - $sum[1])) ? true : false;
}
Example use
for($i = 0; $i < 10; $i++) var_dump(getRandomSaudiId());
/*
Output:
int(2933617506)
int(2409806096)
int(1072585118)
int(2891306413)
int(1810304558)
int(2591965856)
int(1363032527)
int(1031823269)
int(1265954048)
int(2498099472)
int(1134172537)
*/

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 for loop not starting at 0

So, I have code like this at the start of a bigger set of loops
for ($k=1;$k<=60-$jrow['blocks'];$k += $jrow['blocks'])
{
for ($j=0;$j=(count($sarray)-1);$j++)
{
The size of $sarray is 2
Now, when I apply this:
if (isset($j) AND $k == 1)
{
echo "<h1>".$j."</h1>";
}
I get an output of 1. Now clearly $k is still in it's first iteration, but it seems like $j has somehow skipped onto it's second and isn't starting at 0. What am I doing wrong.
Whole code, if required:
for ($k=1;$k<=60-$jrow['blocks'];$k += $jrow['blocks'])
{
for ($j=0;$j=(count($sarray)-1);$j++)
{
if (isset($j) AND $k == 1)
{
echo "<h1>".$j."</h1>";
}
for ($l=$k;$l=($k+$jrow['blocks']-1);$l++)
{
$uid = $sarray[$j];
$staffquery = $hsdbc->prepare("SELECT * FROM user WHERE userID = :uid");
$staffquery->bindParam(':uid',$uid);
$staffquery->execute();
$staffid = $staffquery->fetch(PDO::FETCH_ASSOC);
if (isset($staffid['userid']))
{
echo "<h1>staff query orking</h1>";
die();
}
if ($staffid['complevel'] > $jrow['complevel'])
{
if ($l + ($jrow['blocks'] - 1) < 20 * $i)
{
$schedquery = $hsdbc->prepare("SELECT * FROM schedule WHERE slot = :sn");
$schedquery->bindParam(':sn',$l);
$schedquery->execute();
$schedrow = $schedquery->fetch(PDO::FETCH_ASSOC);
if ($schedrow['jobID'] == 0)
{
for ($m=$l;$m=($l+$jrow['blocks']-1);$m++)
{
$setquery = $hsdbc->prepare("UPDATE schedule SET jobID = :jid WHERE userID=:uid AND slot = :sn");
$setquery->bindParam(':jid',$jrow['jobID']);
$setquery->bindParam(':uid',$staffid['userid']);
$setquery->bindParam(':sn',$m);
$setquery->execute();
}
$cjobquery = $hsdbc->prepare("UPDATE job SET statusID = 1 WHERE jobID = :jid");
$cjobquery->bindParam(':jid',$jrow['jobID']);
$cjobquery->execute();
Break 6;
}
}
}
}
}
}
I think you meant to write. This is probably a typo.
for ($j=0;$j<=(count($sarray)-1);$j++)
$j = (count($sarray)-1)
this is an assignment, use the == operator for equality comparison, or <=, >= for order comparison.

Split total into 5 different numbers

Ok what i'm wanting to do is split a number ($row['count']) into 5, this is easy enough if you want equal numbers:
$sum = ($row['count'] / 5);
$fsum = floor($sum);
but I want each number to be different and still add up to total ie $row['count'] how can this be achieved?
Update:
If this helps its to be used to update 5 rows in a database:
$query = "SELECT * FROM foo";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$sum = ($row['count'] / 5);
$fsum = floor($sum);
$id = $row['id'];
$update = "UPDATE foo SET foo1='$fsum', foo2='$fsum', foo3='$fsum', foo4='$fsum', foo5='$fsum' WHERE id='$id'";
mysql_query($update);
}// while
so ideally the $update query would be something like:
$update = "UPDATE foo SET foo1='$fsum1', foo2='$fsum2', foo3='$fsum3', foo4='$fsum4', foo5='$fsum5' WHERE id='$id'";
This is my take:
function randomize($sum, $parts) {
$part_no = count($parts);
$continnue_counter = 0;
while (count(array_unique($parts)) != $part_no) {
$changing = array_rand($parts, 2);
if (($parts[$changing[0]] - 1) == 0 || ($parts[$changing[1]] - 1) == 0) { // don't let them go under 1
++$continnue_counter;
// sometime one element get everything and others even out on 1
// just throw away everything you got so far and start over
if ($continnue_counter > 10) {
$parts = setup($sum, $part_no);
$continnue_counter = 0;
}
continue;
}
$continnue_counter = 0;
$signum = mt_rand(0, 100) % 2 ? 1 : -1;
$delta = $signum * mt_rand(1, min($parts[$changing[0]] - 1, $parts[$changing[1]] - 1)); // -1 to make sure they don't go under 0
$parts[$changing[0]] += $delta;
$parts[$changing[1]] -= $delta;
}
return $parts;
}
function setup($sum, $part_no) {
$parts = array_fill(0, $part_no, (int)($sum / $part_no));
// acount for the reminder of (int) cast
$reminder = $sum - array_sum($parts);
while ($reminder) {
$parts[array_rand($parts)] += 1;
--$reminder;
}
return $parts;
}
$part_no = 5;
$sum = 42;
$parts = randomize($sum, setup($sum, $part_no));
var_export($parts);
print array_sum($parts)
Update:
I've added a version that introduces a little more entropy.
Update2:
The more random one had a tendency to decrement everything to 1 except one part, added an explicit detection to deal with this. Still the algorithm behind it has unknown termination time.

Categories