getting the even index of a string - php

hey guys im trying to get the even indexes of a string from the db then save them in a variable then echo. but my codes seems doesnt work. please help. here it is
require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section
WHERE school_id = '$school_id'
AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$public_key = $row['public_key'];
}
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
if($key % 2 == 0) {
$priv_key_extract += $public_key[$key];
} else {
$priv_key_extract ="haiiizzz";
}
}
}
echo $priv_key_extract;
as you can see im trying to use modulo 2 to see if the index is even.

I have updated your code as below, it will work now :
<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
//Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
if($key % 2 == 1) {
// Changed concatenation operator , += replaced with .=
$priv_key_extract .= $public_key[$key];
} /*else {
//Commented this as it is getting overwritten
$priv_key_extract ="haiiizzz";
}*/
}
}
echo $priv_key_extract;
?>

Try this function
function extractKey($key) {
if (empty($key) || !is_string($key)) return '';
$pkey = '';
for ($i=0;$i<strlen($key);$i++) {
if ($i % 2 == 0) {
$pkey .= $key[$i];
}
}
return $pkey;
}
echo extractKey('12345678'); # => 1357

Related

Assign the same rank to student with the same scores

I'm assigning ranks to students based on their scores but I encountered a problem where if two or more students have the same scores they are given different ranks.
E.G John, Rita, and Mary scored 76. John is 1st, Rita is 2nd, and Mary is 3rd.
John ==> 76
Rita ==> 76
Mary ==> 76
Bukky ==>74
I want three of them to have the rank as 1st.
John ==> 76
Rita ==> 76
Mary ==> 76
Bukky ==>74
public function getStudentpositionOnlyClass($student_id, $class_id, $terms)
{
$array_product = array();
if ($class_id == 22 || $class_id == 23) {
if ($terms == 'f') {
$totField = 'ft_tot_score';
$table = 'ftscores_rn';
} elseif ($terms == 'm') {
$totField = 'mt_tot_score';
$table = 'mtscores_rn';
} elseif ($terms == 's') {
$totField = 'tot_score';
$table = 'scores_rn';
} elseif ($terms == 'h') {
$totField = 'h_tot_score';
$table = 'hscores_rn';
}
} else {
if ($terms == 'f') {
$totField = 'ft_tot_score';
$table = 'ftscores_primary';
} elseif ($terms == 'm') {
$totField = 'mt_tot_score';
$table = 'mtscores_primary';
} elseif ($terms == 's') {
$totField = 'tot_score';
$table = 'scores_primary';
} elseif ($terms == 'h') {
$totField = 'h_tot_score';
$table = 'hscores_primary';
}
}
$fail = 0;
$pass = 0;
$resultlist = $this->student_model->fullSearchByClass($class_id);
foreach ($resultlist->result_array() as $key => $stdName) {
$idd = $key + 1;
$mId[$idd] = $stdName['pstudent_id'];
$totalSubMarks = $this->db->query(
"SELECT mts.subject_id
FROM " . $table . " mts
LEFT JOIN subjects sub ON(sub.id=mts.subject_id)
WHERE class_id=" . $class_id .
" AND mts.subject_id IS NOT NULL
GROUP BY mts.subject_id ORDER BY sub.name");
$gtotal = 0;
$totSubjects = 0;
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'],
$stdName['pstudent_id'], $table, $totField);
// //// set mtotalmark
$gtotal = $gtotal + $totalMarks;
// //// set mgtotal
$mGTotal[$idd] = $gtotal;
if ($totalMarks != 0) {
$totSubjects = $totSubjects + 1;
}
// //// set mAvg
if ($totSubjects != 0) {
$mAvg[$idd] = round($gtotal / $totSubjects, 1);
} else {
$mAvg[$idd] = 0;
}
}
// /////////
if ($totSubjects != 0) {
$percentage = ($gtotal / $totSubjects);
}
if ($percentage >= 0 && $percentage <= 39.99) {
$fail = $fail + 1;
} else {
$pass = $pass + 1;
}
}
foreach ($mAvg as $dd => $val) {
// if pure numbers store in nums array
if (! is_nan($val)) {
$nums[$dd] = $val;
}
}
arsort($nums);
$id = 1;
foreach ($nums as $kk => $av) {
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'], $mId[$kk], $table,
$totField);
}
if ($student_id == $mId[$kk]) {
return $id;
}
// $array_product['student'.$mId[$kk]]= $id;
$id += 1;
}
}
As mickmackusa stated in his comment you have to memorize the previous score and only increment the rank if the score has changed. As you already order your results we can assume a score change between 2 iterations is always a decrease.
Your variable names are very unintuitive. So maybe my code changes are in the wrong place but you shoud understand the concept. I assume that $totSubjects is that score.
Try not to shorten a variable's name too much because you have no benifit but loose that important information on what it is. At least comment a variable assignment if its unclear what the variable holds of.
Change your loop like this:
$previousScore = null; // added THIS
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'],
$stdName['pstudent_id'], $table, $totField);
// set mtotalmark
$gtotal = $gtotal + $totalMarks;
// set mgtotal
$mGTotal[$idd] = $gtotal;
if ($totalMarks != 0) {
if($previousScore != $totalMarks) { // added THIS
$totSubjects = $totSubjects + 1;
} else { // added THIS
$totSubjects = $totSubjects; // keep rank without incrementing
}
}
$previousScore = $totalMarks; // added THIS
// set mAvg
if ($totSubjects != 0) {
$mAvg[$idd] = round($gtotal / $totSubjects, 1);
} else {
$mAvg[$idd] = 0;
}
}
In case $gtotal or any of the other mystic variables ;) is holding the score then try to modify my given code changes to $gtotal. Shouldn't be too hard. In that case just add a comment so I can change my answer that it's actualy correct.
Hope that helps!

PHPExcel: Dynamic Row and Column incrementing is not working for Array in phpexcel?

While printing column and row from an array it's showing blank not exporting any data
$inn_table = "";
if ($result['qualification']['dd1'] != "") {
$dd1 = explode(",", $result['qualification']['dd1']);
}
if ($result['qualification']['dd2'] != "") {
$dd2 = explode(",", $result['qualification']['dd2']);
}
for ($i = 0; $i < count($labels); $i++) {
if ($result['qualification']['dd1'] != "") {
echo '<pre>First';
print_r($dd1); ** //echo arrays**
for ($j = 0; $j < count($dd1); $j++) {
$temp = explode(">", $dd1[$j]);
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd1[$j]);
echo '<pre>First ';
print_r($name[1]); ** //echo names**
}
}
}
}
Here is my Array structure
and Here names which i am trying to export from Array
So i only trying to export names from that array please help
foreach($labels as $ind => $label) {
$index = $ind + 2;
$letter = range('A', 'Z')[$ind2];
$val = explode('>', $data);
$objPHPExcel->getActiveSheet()->setCellValue($letter . $index, $val[1]);
}

MySQLi why am I only getting 1 result?

There are three "BC" in the result_category but I am only getting 1 result. This is for a personality quiz. Please Help. I also tried $query = "SELECT result FROM quiz_map where result_category = 'BC'"; but still, only 1 result is showing.
$result = mysqli_query($link, $query);
$cat_a = $cat_b = $cat_c = $cat_d = $cat_e = 0;
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$cat = $row['category'];
if ($cat == "A") {
$cat_a += 1;
} elseif ($cat == "B") {
$cat_b += 1;
} elseif ($cat == "C") {
$cat_c += 1;
} elseif ($cat == "D") {
$cat_d += 1;
} elseif ($cat == "E") {
$cat_e += 1;
}
}
$array = array('A' => $cat_a, 'B' => $cat_b, 'C' => $cat_c, 'D' => $cat_d, 'E' => $cat_e);
$str = '';
foreach ($array as $i => $value) {
if ($value >= 6) {
$str = $i;
break;
} elseif ($value >= 2) {
$str .= $i;
}
}
$var = sort($array);
$query = "SELECT result FROM quiz_map where result_category = '$str' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
echo $row[0];
?>
There's many things wrong with your code!
As pointed by #IsThisJavascript and #Cashbee:
You are executing a query with a LIMIT 1 statement, it will only return one record.
As pointed by myself:
Doing echo $row[0] will have the same result, if you are only echoing the first value of the array you can't expect to have multiples can you?
As pointed by #IsThisJavascript:
You need to loop the results array, like so:
while($row = mysqli_fetch_array($result)){
echo $row['result_category'];
}
Consider switching the query from a '=' to a '%like%' statement, to maximize results if you want to get the values that partionaly cointain the string.

removing item from result query in codeigniter

I can't remove an item from query result array in php + codeigniter.
This is my code
if($query->num_rows > 0)
{
$rows = $query->result();
foreach ($rows as $key => $row)
{
$i = 0;
$fornecedor = $row->fornecedor;
$marca = $row->marca;
$modelo = $row->modelo;
$versao = $row->versao;
$preco = $row->preco;
foreach ($rows as $row2)
{
$fornecedor2 = $row2->fornecedor;
$marca2 = $row2->marca;
$modelo2 = $row2->modelo;
$versao2 = $row2->versao;
$preco2 = $row2->preco;
if(($fornecedor == $fornecedor2) && ($marca == $marca2) && ($modelo == $modelo2) && ($versao == $versao2) && ($preco == $preco2))
{
$i++;
}
}
if($i > 3)
{
unset($row[$key]);
}
}
return $query;
}
I already checked some examples here in stackoverflow but i cant make this work.
I can't see the problem ty
so $row is a $rows[$key], maybe i don't understand something, but it's seems to me you have to write unset($rows[$key]);

need help with php loop logic

This code works perfectly except that it doesn't print the last 2 rows of my csv file:
This is the file:
603629,0,ATLV0008,"Vendor1",1942.60,11/04/2010,1942.60,9/1-9/30/10,EFT-JP
603627,2,ATLV0008,"Vendor1",1242.40,11/04/2010,1242.40,7/1-7/31/10,EFT-JP
600023,0,FLD4V0003,"Vendor2",1950.00,06/15/2010,1950.00,6/14/10 Request,EFT-JP
600024,0,FLD4V0003,"Vendor2",1800.00,06/15/2010,1800.00,6/14/10 Request,EFT-JP
603631,0,ATLV5066,"Vendor2",1000.00,11/09/2010,1000.00,11/4/10 Check Request,PM2
603647,0,ATLV5027,"DVendor3",2799.80,11/15/2010,2799.80,10/1-10/31/10 Bishop,PM2
603642,5,ATLV5027,"Vendor3",482.40,11/15/2010,482.40,10/1-10/18/10 Allen,PM2
603653,0,ATLV0403,"Vendor4",931.21,11/17/2010,931.21,9/1-9/30/10,EFT-JP
603661,0,ATLV0105,"Vendor5",26.75,11/19/2010,26.75,093139,PM2
603660,1,ATLV0105,"Vendor5",5.35,11/19/2010,5.35,093472,PM2
Here is the code: (It needs to display the sum of 2 rows with the same vendor before the actual rows)
if (($handle = fopen('upload/ATLANTA.csv', "r")) !== FALSE) {
while (($row_array = fgetcsv($handle, 1000, ","))) {
foreach ($row_array as $key => $val) {
$row_array[$key] = trim(str_replace('"', '', $val));
ob_flush();
}
$complete[] = $row_array;
ob_flush();
}
}
flush();
$prevVendor = '';
$sum = 0;
$venData = '';
if (isset($complete)) {
foreach ($complete as $key => $val) {
$venData .= "<br/>";
$currVendor = $complete[$key][3];
if ($currVendor != $prevVendor){
if ($prevVendor != NULL){
print "<br/>";
print $sum . "<br/>";
print $venData;
$sum = 0; $venData = '';
}
}
foreach ($val as $ikey => $ival){
if ($ikey != 1){
$venData .= $ival . '&nbsp';
$prevVendor = $val[3];
}
}
if ($currVendor == $prevVendor){
$sum += $complete[$key][6];
}
}
}
I don't really understand your problem but if you want to get (and save it wherever you want) the sum of each vendors, you should do something like this :
$prevVendor = null;
$venData = '';
$sums = array();
if (isset($complete) && is_array($complete)) {
$lim = count($complete);
for ($key=0;$key<$lim;++$key) { // no need foreach for simple array
$venData .= "<br/>";
$currVendor = $complete[$key][3];
if ($currVendor != $prevVendor){
if ($prevVendor != null){
print "<br/>";
print $venData;
}
$venData = '';
$prevVendor = $currVendor;
$sums[$currVendor] = 0; // set the counter to 0
}
foreach ($complete[$key] as $ikey => $ival){
if ($ikey != 1){
$venData .= $ival . ' '; // is useful for you I guess
}
}
$sums[$currVendor] += $complete[$key][6]; // add amounts
}
}
if ($prevVendor != null){ // you need to do this to display the last record
print "<br/>";
print $venData;
}
var_export($sums); // check results
This can be some syntax errors ...

Categories