Get Max value from db and add one - php

I have a table that contain a sequence like this B05/FDH/CN/NM/00001, B05/FDH/CN/NM/00002
I need to get the max value from DB and add 1 to the sequence. the next number would be B05/FDH/CN/NM/00003
how do i do this
SQL and im getting max value as B05/FDH/CN/NM/00002
select MAX(`coverNoteNo`) as cnumber from covernotenonmotor where users_idusers = 8

Try this at Databse Level. this may help You in Code Optimization :)
select max(coverNoteNo), (SUBSTRING( max(coverNoteNo),0 , 15))+cast(cast((SUBSTRING( max(coverNoteNo),15 ,20)) as int)+1 as varchar) from covernotenonmotor

Save the result into a string then try this..
$string = 'B05/FDH/CN/NM/00002';
$stringpart = substr($string, 0, -5); // "B05/FDH/CN/NM/"
$numberpart = (integer) substr($string, -5); // "2"
$numberpart = $numberpart+1; // "3"
$numberpart = str_pad($numberpart, 5, "0", STR_PAD_LEFT); // "00003"
echo $result = $stringpart.$numberpart; // "B05/FDH/CN/NM/00003"

If you are fetching data as array from database you can also try this -
Assume you have fetched a array result set i.e. $arr than you can increment in a loop -
$arr = array('B05/FDH/CN/NM/00001', 'B05/FDH/CN/NM/00002'); //values from db
$b =array();
foreach($arr as $a)
{
$str = substr($a, 0, -5);
$b[] .= $str.str_pad(substr($a, -5) + 1, 5, "0", STR_PAD_LEFT);
}
print_r($b); //Array ( [0] = B05/FDH/CN/NM/00002 [1] = B05/FDH/CN/NM/00003 )

Related

How to find the sum of the values of this time series data set?

My controller is returning a time-series array for a graph, it also needs the total views count. The array it returns is in this format, need to calculate the sum of views corresponding ot the dates.
framework: Laravel
[
{
"2021-04-30": 0,
"2021-05-01": 0,
"2021-05-02": 0,
"2021-05-03": 0,
"2021-05-04": 0,
"2021-05-05": 0,
"2021-05-06": 1
}
]
$result = $as->getVisits();
$array = json_decode($result,1);
$total = 0;
foreach($array[0] as $date => $visits)
$total += 1;
echo $total;
return [$result, $total];
This look like a JSON array, you need first to decode it in a php array and then loop it to make the sum if you want to control over the dates
$array = json_decode($json,1);
$sumVisits = 0;
foreach($array[0] as $date => $visits)
$sumVisits += 1;
echo $sumVisits;
Or if you just want to sum everything you can use array_sum as pointed out in the comments by El_Vanja
$array = json_decode($json,1);
echo array_sum(array[0]);

How do I get a column in CSV in reverse order into php?

I would like to know how can I get a specific column (in my case the second column) from CSV in reverse order into PHP? For example if my file is
my, name, is, marwan
here, goes, thing, some
1, 2, 3, 4
Now the output the I want in php would be
my - some - 1
name - thing - 2
is - goes - 3
marwan - here - 4
My existing PHP code for printing everything in normal order is
for($num = 1; $num <= 1; $num++) {
if(file_exists('1.csv')) {
$csvData = file_get_contents('1.csv');
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) { $array[] = str_getcsv($line); }
// count number of columns and minus 1 from it
$count = count($array[0]) - 1;
for ($x = 0; $x <= $count; $x++) {
$first_column = $array[0][$x];
$second_column = $array[1][$x];
$third_column = $array[2][$x];
// Now just outputting the values...
";
}
}
}
Thank you.
Well, you can do it easily:
<?php
// defining a test array similar to yours
$records = array(
array(1, 'abc', '111'),
array(2, 'def', '222'),
array(3, 'ijk', '333'),
array(4, 'lmn', '444'),
array(5, 'opq', '555'),
);
// getting the column and reversing it
$col1rev = array_reverse(array_column($records, 1));
?>
You need to first make the CSV in to an array then reverse the second line.
Once that is done you foreach the first item in the array and use the key to output the other values.
$arr = explode("\n", $csv);
Foreach($arr as $key => &$line){
$line = explode(", ", $line);
If($key == 1) $line = array_reverse($line);
}
Unset($line);
Foreach($arr[0] as $key => $val){
Echo $val . "\t-\t" . $arr[1][$key] . "\t-\t" . $arr[2][$key] ."\n";
}
Output:
// The output here on SO looks odd but in reality it's tab separated
my - some - 1
name - thing - 2
is - goes - 3
marwan - here - 4
https://3v4l.org/MNLLF

Get the name of the variable which has the second lowest/smallest value with PHP

I have 4 variables and each of those have an integer assigned to them. Could anybody please let me know how I can get the name of the variable which has the second smallest value?
Thanks.
Use compact to set the variables to one array, sort the array, then use array slice to get the second value.
Then optionally echo the key of the second value.
$a = 2;
$b = 7;
$c = 6;
$d = 1;
$arr = compact('a', 'b', 'c', 'd');
asort($arr);
$second = array_slice($arr,1,1);
Echo "variable name " . Key($second) ."\n";
Echo "value " . ${key($second)};
https://3v4l.org/SVdCq
Updated the code with how to access the original variable from the array
Unless you have a structured way of naming your variables eg prefix_x there is no real way.
Recommended way is using an array like this:
$array = array(
"a" => 3,
"b" => 2,
"c" => 1,
"d" => 6
);
// Sort the array descending but keep the keys.
// http://php.net/manual/en/function.asort.php.
asort($array);
// Fetch the keys and get the second item (index 1).
// This is the key you are looking for per your question.
$second_key = array_keys($array)[1];
// Dumping the result to show it's the second lowest value.
var_dump($array[$second_key]); // int(2).
To be more in line with your question you can create your array like this.
$array = array();
$array['variable_one'] = $variable_one;
$array['some_random_var'] = $some_random_var;
$array['foo'] = $foo;
$array['bar']= $bar;
// Same code as above here.
Instead of using 4 variables for 4 integer values, you can use an array to store these values. Sort the array and print the second index of the array i.e. 1.
<?php
$x = array(2,3,1,6);
$i = 0, $j = 0, $temp = 0;
for($i = 0; $i < 4; $i++){
for($j=0; $j < 4 - $i; j++){
if($x[$j] > $x[$j+1]){
$temp = $x[$j];
$x[$j] = $x[$j+1];
$x[$j+1] = $temp;
}
}
}
for($j = 0; $j < 4; $j++){
echo $x[$j];
}
echo $x[1];
?>
First you need to have all Variables in an Array. You can do this this way:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
or this way:
$array['a'] = 3;
$array['b'] = 6;
// etc
Then you need to sort the Items with natsort() to receive a natural Sorting.
natsort($array);
Then you flip the Array-Keys with the Values (In Case you want the Value, skip this Line)
$array = array_flip($array);
After this you jump to the next Item in the Array (Position 1) by using next();
echo next($array);
Makes in Total a pretty short Script:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
natsort($array);
$array = array_flip($array);
echo next($array);

Insert new element in an array

EDITED
$queryPremium ="Select * from tablename where premium = 1 order by id desc";
$rowPremium = mysql_query($queryPremium);
$queryNotPremium ="Select * from tablename where premium = 0 order by id desc";
$rowNotPremium = mysql_query($queryNotPremium);
now i want a single array where the order of the rowNotPremium will be maintained and $rowPremium will be inserted randomly after 2 data of $rowNotPremium or after 3data of $rowNotPremium...
How to do that?
you can do this:
$newArray = $nonpremium + $premium
or
$newArray = array_merge($nonpremium, $premium)
Sorry for any bad practice here if you feel this can be edited please edit it...
<?php
$arr_a = array('1','2','3','4','5','6');
$arr_b = array('apples','oranges','bananas','peaches');
// How many elements are in the array we are inserting into
$count = count($arr_a);
// What was the last insert position? Make sure the next will be greater than this
$prev = 0;
// Loop through each of our elements to insert
foreach($arr_b as $value)
{
// Generate a random value, higher than the previous
// random number but still less than count($arr_a)
$rand = rand($prev, $count);
// Store this as the previous value + 1
$prev = $rand + 1;
// Insert our value into $arr_a at the random position
array_splice($arr_a, $rand, 0, $value);
}
echo "<pre>".print_r($arr_a, true)."</pre>";
Use array_splice() and rand() functions
$array1 = array( 1,2,3,4,5 );
$array2 = array( 6,7,8,9 );
array_splice( $array1, rand(0,count($array2)-1), 0, $array2 ); // splice in at random position

Knowing the length of each sequence in a string

I have a string like this "0011100001100111", and i would like to know the length of each sequence (00, 111, 0000, 11, 00, 111), in the right order.
How can I do that in PHP ?
Thanks to who will help me.
create a loop that loops through the entire string. It would look at each character in the string and compare it to the previous character. If it is the same, then it increases a counter, if it is different, it pushes the counter value onto an array and clears the counter.
Untested code:
function countSequenceLengths($str){
$counter = 1;
$lastChar = $str[0];
$ret = array();
for($i=1; $i<=strlen($str); $i++){
if($i<strlen($str) && $str[$i] == $lastChar){
$counter++;
}else{
$ret[] = $counter;
$counter = 1;
$lastChar = $str[$i];
}
}
return $ret;
}
You could use a regular expression to do that:
preg_split('/(?<=(.))(?!\\1)/', $str)
Here you’re getting an additional empty string at the end that you just need to remove:
array_slice(preg_split('/(?<=(.))(?!\\1)/', $str), 0, -1)
The code I made, with your help :
$string = "1111100111111001111110011111100111111001111... ...10011111100111111001";
$str = substr($string, 10, 12);
echo "str = '".$str."'<br />";
$array = array_slice(preg_split('/(?<=(.))(?!\\1)/', $str), 0, -1);
for($i=0; $i<count($array); $i++){
echo "array[".$i."] = '".$array[$i]."', ";
echo "array[".$i."] length = '".strlen($array[$i])."'<br />";
}
returns me the values I needed :
str = '111001111110'
array[0] = '111', array[0] length = '3'
array[1] = '00', array[1] length = '2'
array[2] = '111111', array[2] length = '6'
array[3] = '0', array[3] length = '1'
Thanks a lot !

Categories