changing a value in array - php

I have an array
N America | S America | Europe | Asia | (blank)
I am trying to make a query of it. But I want to change some values. I have a code like this:
if (!empty($md)) {
$mds = '';
if(count($md) > 0 ){
$mds .= 'AND ( FALSE';
foreach($md as $key => $value){
if ($key == '(blank)') {
$value ='';
$mds .= " OR data.m = '$value'";
} else {
$mds .= " OR data.m = '$value'";
}
}
$mds .= ') ';
}
}
And actually it finds the '(blank)' value and change it to ''. But it at the end all I get is:
AND (FALSE
OR data.m = ''
OR data.m = 'S America'
OR data.m = 'Europe'
OR data.m = 'Asia'
OR data.m = '(blank)')
It seems like it change the first value to my '' and unfortunately there is still '(blank)' at the end.
My question is how to change a value in an array in a correct way?

You need to check if $value is '(blank)' not the key, so:
if ($value == '(blank)') { ... }
For a simple array like $x = array('First','Second'); When you look over the array in a foreach, $key will be the index, so $x[0] would be the value 'First'.

Change 7 line to:
if ($value == '(blank)') {
My scripts works with first value:
$md = Array('N America','S America','Europe','Asia','(blank)');
if (!empty($md)) {
$mds = '';
if(count($md) > 0 ){
$mds .= 'AND ( FALSE';
foreach($md as $key => $value){
if ($value == '(blank)') {
$value ='';
$mds .= " OR data.m = '$value'";
} else {
$mds .= " OR data.m = '$value'";
}
}
$mds .= ') ';
}
}
AND ( FALSE OR data.m = 'N America' OR data.m = 'S America' OR data.m = 'Europe' OR data.m = 'Asia' OR data.m = '')

Related

How to change direction of calculation for values in a table using PHP

I have a table with columns
-Deposits
-Withdrawals
-Running Balance
I am using the values inside the first two columns to calculate the Running balance in the Running Balance column.
The issue.
The calculation is working fine - just that it's doing so in reverse. If you look at the "Entry Id" column, I have the entry Ids which I would like to use for the calculation, or whichever way works. If we use the Entry ID column then I need the calculation to happen from the smallest to the largest Entry ID.
Here is my code.
function display_form_entries_shortcode() {
global $wpdb;
$form_id = 73;
$current_user_id = get_current_user_id();
$entries = FrmEntry::getAll(array('form_id' => $form_id, 'user_id' => $current_user_id), ' ORDER BY created_at DESC', '', true, 999999);
if(empty($entries)) {
return 'No entries found for form ID '.$form_id.' for user ID '.$current_user_id;
}
$form_fields = FrmField::get_all_for_form($form_id);
$field_labels = array();
foreach ($form_fields as $field) {
$field_labels[$field->id] = $field->name;
}
$table_name_n = $wpdb->prefix . 'frm_fields';
$table_name = $wpdb->prefix . 'frm_item_metas';
// Add the new columns
$field_labels[787] = "Deposits";
$field_labels[788] = "Withdrawals";
$field_labels[789] = "Running Balance";
$output = '<table>';
$output .= '<tr><th>' . implode('</th><th>', $field_labels) . '</th></tr>';
$running_balance = 0;
global $m_field;
foreach ($entries as $entry) {
$entry_values = array();
foreach ($field_labels as $field_id => $field_label) {
$field_value = '';
if ($field_id == 746) { //return "Select Account" field
$row = $wpdb->get_row( "SELECT * FROM $table_name_n WHERE field_key = 'f2ego'" );
$options = unserialize( $row->options );
$fieldi_value = $options[FrmEntryMeta::get_entry_meta_by_field($entry->id, $field_id)];
}
//Running Balance Calculations
if ($field_id == 787) {
if ($entry->metas[783] == 'Money In' && $fieldi_value == $m_field) {
$field_value = $entry->metas[727] ? $entry->metas[727] : $entry->metas[738];
if ($entry->metas[736]) {
$field_value -= $entry->metas[736];
}
$field_value = $field_value > 0 ? $field_value : 0;
$running_balance += $field_value;
} else {
$field_value = 0;
}
} else if ($field_id == 788 && $fieldi_value == $m_field) {
if ($entry->metas[783] == 'Money Out') {
$field_value = $entry->metas[727] ? -$entry->metas[727] : -$entry->metas[738];
if ($entry->metas[736]) {
$field_value += $entry->metas[736];
}
$field_value = $field_value < 0 ? $field_value : 0;
$running_balance += $field_value;
} else {
$field_value = 0;
}
}
else if ($field_id == 789 && $fieldi_value == $m_field) {
$field_value = $running_balance;
}
else {
$field_value = FrmEntryMeta::get_entry_meta_by_field($entry->id, $field_id);
}
//End of calculations
$entry_values[] = $field_value;
}
if(!in_array($m_field, [$entry_values[1], $entry_values[11], $entry_values[16]])) {
continue;
}
if (!empty($entry_values)) {
$output .= '<tr><td>' . implode('</td><td>', $entry_values) . '</td></tr>';
}
}
$output .= '</table>';
return $output;
}
add_shortcode('display_form_entries', 'display_form_entries_shortcode');
I have run out of options trying to force the calculation in order of the Entry IDs. Any assistance is welcome.

Problem adding operator condition to the string

I need to add AND or OR in-between my Query string. My conditions are as follows:
first case:
$array = [
"month" => "October",
"year" => 2020,
"information => "October 2020"
];
In this case, i need
"(MONTH(b.day) = 'October' AND YEAR(b.day) = '2020') OR b.information LIKE '%October 2020%'"
second case:
$array = [
"month" => "October",
"information => "October 2020"
];
In this case, i need
"(MONTH(b.day) = 'October') OR b.information LIKE '%October 2020%'"
I have tried following lines of code but I couldn't fix the AND OR in correctly.
$whereStr = '';
$alias = "b.";
$orCounter = 0;
$andCounter = 0;
$dateMonth = false;
if (array_key_exists('year', $array) && array_key_exists('month', $array)) {
$dateMonth = true;
}
foreach ($array as $key => $value) {
if (0 !== $orCounter) {
$whereStr .= ' OR ';
} elseif ($andCounter > 0 && true === $dateMonth) {
$whereStr .= ' AND ';
}
if ('month' === $key || 'year' === $key) {
++$andCounter;
echo $andCounter;
$whereStr .= strtoupper($key) . '(' . $alias . 'day' . ')';
$whereStr .= "= '$value'";
if ($andCounter === 2) {
++$orCounter;
}
continue;
}
if ('type' === $key) {
$whereStr .= "$alias$key IN ($value)";
continue;
}
$whereStr .= "$alias$key LIKE '%$value%'";
++$orCounter;
}
Can anybody please help me fix this?
just use simple if else conditions why using loop
$where ='';
if(isset($array['month']) && isset($array['year']) && isset($array['information'])){
$where = '(MONTH(b.day) = '".$array['month']."' and YEAR(b.day) = '".$array['year']."' ) or b.information like "%'.$array['information'].'%" ';
}else if(isset($array['month']) && !isset($array['year']) && isset($array['information']))
{
$where = '(MONTH(b.day) = '".$array['month']."' ) or b.information like "%'.$array['information'].'%" ';
}
It's cleaner with arrays:
$AND[] = "`fieldA` = 'Bar'";
$AND[] = "`fieldB` = 'Foo'";
$andString = implode(' AND ',$AND);
$andString is
`fieldA` = 'Bar' AND `fieldB` = 'Foo'
So your code can be
$qq = "SELECT * from foobar WHERE $andString";

PHP function - How to take three fields and perform and action when the first, 2nd and last field are the same but on different rows of a file

I have file that is delimetered by a comma like below
Big2,red,0,Y
Big2,blue,0,N
Big2,green,1,N
Big6,red,0,Y
Big6,blue,0,N
Big6,green,1,N
Big6,yellow,0,Y
Big6,black,0,Y
Following is the code I used to read the file
$file_content = explode("\n",(file_get_contents("inven.csv")));
foreach ($file_content as $key => $value) {
$value = str_replace(array('\'', '"'), '', $value);
$line_records = explode(',', $value);
$reference = trim($line_records[0]);
$option = trim($line_records[1]);
$quantity = trim($line_records[2]);
$discontinued = trim($line_records[3]);
}
I want to check for the following condition and perform some action
If the 1st, 2nd and 4th field are the same for all lines
If all "Big2" rows have the 3rd field = 0 and the 4th field = Y
Hope this solves your problem
$references = $options =$quantities = $status = array();
$file_content = explode("\n",(file_get_contents("inven.csv")));
foreach ($file_content as $key => $value) {
$value = str_replace(array('\'', '"'), '', $value);
$line_records = explode(',', $value);
$references[] = trim($line_records[0]);
echo end($references);
$options[] = trim($line_records[1]);
echo end($options);
$quantities[] = trim($line_records[2]);
echo end($quantities);
$status[] = trim($line_records[3]);
echo end($status);
}
$flag = true;
foreach(array_combine($references, $quantities, $status) as $ref => $quantity => $stat) { // foreach line throws and error
if($ref == 'Big2') {
if($quantity != 0 || $stat != 'Y'){
$flag = false;
break;
}
}
}
if (count(array_unique($references)) === 1 && count(array_unique($options))==1 && count(array_unique($status))==1) {
//Do action if the 1st, 2nd and 4th field are the same for all lines
}
if ($flag) {
//Do action if all "Big2" rows have the 3rd field = 0 and the 4th field = Y
}

getting the even index of a string

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

check for empty array and remove empty array

i have 100 values in array ,need to check first ten values are not empty and all elements should be same count if not unset the values ,i using "|" for combing all the values ,
I have all the values implode with "|" below is the function which im using im not getting final results as required ,finalvalues is given below ,can you please help fixing this issue
finalvalues =array(
"3" =>"Education|Category|Roles|Industry|Address|Email|Phone|Mobile",
"4" => "Bsc|computer|SE|Computers||test#test.com|123123132|123234234234"
);
$values = array(
"0"=> "Computer Student History",
"1"=> "Computer Student History",
"2"=> "Computer Student History|batch number",
"3" => "| | | | | | | | | | | | | | | | ",
"4" => "Education|Category|Roles|Industry|Address|Email|Phone|Mobile",
"5" => "Bsc|computer|SE|Computers||test#test.com|123123132|123234234234"
);
$newVal = array();
foreach ($values as $key => $val) { //$values it is..
$prevalues = explode('|', $val);
$finalvalue = array_empty($prevalues ,$full_null=true);
if($finalvalue == 1){
unset($prevalues); //why??
}else{
$vales = implode('|', $prevalues);
$newVal[$key] = $vales; //use $key, to preserve the keys here..
}
}
print_r($newVal); //output
function array_empty($ary, $full_null=false){
unset($prevKey);
$count = array();
$null_count = 0;
$ary_count = count($ary);
if ($ary_count == 1) //this means there was no '|', hence no split.
return 1;
foreach($array_keys($ary) as $value){
// echo $value;
//trying check if first value is less then second value unset array similar second is less then third value unset second .. so the all the array values is same count
$count[$value] = count($ary[$value]);
if (isset($prevKey) && $count[$prevKey] !== $count[$value]) {
//unset($array[$prevKey]);
return 1;
}
if($value == NULL || trim($value) == "" ){ // trim(..) was what you wanted.
$null_count++;
}
}
if($full_null == true){
if($null_count == $ary_count){
return 1;
}else{
return 0;
}
}
}
This should help you (with inline comments):
$newVal = array();
foreach ($values as $key => $val) { //$values it is..
$prevalues = explode('|', $val);
$finalvalue = array_empty($prevalues ,$full_null=true);
if($finalvalue == 1){
unset($prevalues); //why??
}else{
$vales = implode('|', $prevalues);
$newVal[$key] = $vales; //use $key, to preserve the keys here..
}
}
print_r($newVal); //output
function array_empty($ary, $full_null=false){
$null_count = 0;
$ary_count = count($ary);
if ($ary_count == 1) //this means there was no '|', hence no split.
return 1;
foreach($ary as $value){
// echo $value;
if($value == NULL || trim($value) == "" ){ // trim(..) was what you wanted.
$null_count++;
}
}
if($full_null == true){
if($null_count == $ary_count){
return 1;
}else{
return 0;
}
}
}
Here are some much simpler, not crazy ways
PHP 5.3+
$final = array_filter(
$values,
function( $v ){
return
preg_replace( '~\s*\|\s*~', '', $v ) &&
count( explode( '|', $v ) ) === 8;
}
);
PHP < 5.3
This edits the $values array directly
foreach( $values as $k => $value ) {
if ( preg_replace( '~\s*\|\s*~', '', $value ) == '' || count( explode( '|', $value ) ) !== 8 ) {
unset( $values[$k] );
}
}

Categories