Shorten if else statement using php - php

i have a question about shorten if else statement. I am trying to make a weather application using OpenWeatherMap api. But i don't like those icons. I want to change the icons like this:
if($desc == 'clear sky'){
$weather_icon = 'clear_sky.png';
}else
if($desc == 'few clouds'){
$weather_icon = 'few_clouds.png';
}else
if($desc == 'scattered clouds'){
$weather_icon = 'scattered_clouds.png';
}else
if($desc == 'broken clouds'){
$weather_icon = 'broken_clouds.png';
}else
if($desc == ''){
.....
}
......
So my question is how can i do this with shorten if else or do you have any idea to use different thinks?

Arrays are the glue that holds the universe together (if the universe is written in PHP).
$map = [
'clear sky' => "clear_sky.png",
'few clouds' =>"few_clouds.png",
'scattered clouds' => 'scattered_clouds.png'
'broken clouds' => 'broken_clouds.png'
];
if (isset($map[$desc])) {
$weather_icon = $map[$desc];
}
This allows you to also map unrelated words with image names as well as multiple words to the same image.

Since your description matches what you're looking for you could do this.
if (
in_array(
$desc,
array(
'clear sky',
'few clouds',
'scattered clouds',
'broken clouds'
)
)
) {
$weather_icon = str_replace(' ', '_', $desc) . '.png';
}
Another option would be to use a map, they they don't always match.
$map = [
'clear sky' => 'clear_sky.png',
'few clouds' => 'few_clouds.png',
'scattered clouds' => 'scattered_clouds.png',
'broken clouds' => 'broken_clouds.png',
'thunderstorm with light rain' => 'few_clouds.png',
];
// $api['icon'] references the original icon from the api
$weather_icon = array_key_exists($desc, $map) ? $map[$desc] : $api['icon'];

If your weather patterns are predictable, you can just use a one liner:
$img = str_replace ( ' ' , '_', $desc ) . '.png';
However if you have a list that you cannot just alter dynaically you can use this:
$descriptions = [
'clear sky'=>'clear_sky',
'few clouds'=>'few_clouds',
'scattered clouds'=>'scattered_clouds',
'broken clouds'=>'broken_clouds',
];
$defaultImg = 'some_empty';
$img = !empty($desc) ? $descriptions[$desc] : $defaultImg;
$img = $img . 'png';

<?php
$desc = "clear sky";
$weather_icon = str_replace(" ","_",$desc).".png";
echo $weather_icon;
?>

It looks like you have a some fixed notation. You could use this:
<?php
$desc = 'clear sky';
convertDescriptionToImage( $desc );
function convertDescriptionToImage( $description )
{
$arrayCodes = ["clear sky", "few clouds"];
if ( TRUE == in_array( $description, $arrayCodes ) )
{
return str_replace( " ", "_", "$description.png" );
}
die( "$description not found" );
}

Related

Laravel 5.6 Ajax Post 500 Internal Server Error

Hello i am sending large string data via Ajax Post Request and its working fine on localhost but not working on live server i am sending some image data then this image data is converted to images on server..also its taking so much time to send this data average data size is between 4 to 7 MB..also can you suggest a better way so it can be done quickly..also things are setup properly i am including CSRF token and URL is also good but don't know why this error is occurring
Error => Status Code: 500 Internal Server Error
My controller code where i am sending request
$pid = $request->input('id');
$pt_id = $request->input('pt_id');
$pname = $request->input('name');
$isBack = $request->input('isBack');
$qty = $request->input('qty');
$paper = $request->input('paper');
$previewFront = $request->input('previewFront');
$previewBack = $request->input('previewBack');
$PrintDataFront = $request->input('PrintDataFront');
$PrintDataBack = $request->input('PrintDataBack');
$cart_item_id = uniqid();
//Store Img Data
$pf = str_replace('data:image/png;base64,', '', $previewFront);
$pf = str_replace(' ', '+', $pf);
$pf_n = $cart_item_id.'_f_.'.'png';
\File::put(public_path(). '/cart_preview/' . $pf_n, base64_decode($pf));
$pb = str_replace('data:image/png;base64,', '', $previewBack);
$pb = str_replace(' ', '+', $pb);
$pb_n = $cart_item_id.'_b_.'.'png';
\File::put(public_path(). '/cart_preview/' . $pb_n, base64_decode($pb));
$pdf = str_replace('data:image/png;base64,', '', $PrintDataFront);
$pdf = str_replace(' ', '+', $pdf);
$pdf_n = $cart_item_id.'_f_.'.'png';
\File::put(public_path(). '/orders/' . $pdf_n, base64_decode($pdf));
$pdb = str_replace('data:image/png;base64,', '', $PrintDataBack);
$pdb = str_replace(' ', '+', $pdb);
$pdb_n = $cart_item_id.'_b_.'.'png';
\File::put(public_path(). '/orders/' . $pdb_n, base64_decode($pdb));
//Get Prices and qty
$opriceitem = PriceTableItem::find($qty);
$itemQty = $opriceitem->qty;
$basePrice = $opriceitem->total;
if($isBack == 'true') {
$backPrice = $opriceitem->total_back;
$itemPrice = $opriceitem->total + $opriceitem->total_back;
$pricePerPiece = $opriceitem->item_price + $opriceitem->item_price_back;
}else {
$backPrice = 'INCLUDED';
$itemPrice = $opriceitem->total;
$pricePerPiece = $opriceitem->item_price;
}
if($paper == 'Premium White') {
$paperPrice = ($itemPrice/100) *60;
$itemPrice = $itemPrice + ($itemPrice/100) *60;
} else {
$paperPrice = 'INCLUDED';
}
//Get all Available Qty
$allQty = PriceTableItem::where('tid', $pt_id)->get();
$allAvailableQty = array();
foreach($allQty as $allqtyarry) {array_push($allAvailableQty, $allqtyarry->qty);}
//Create Cart Object
$item = [
"id" => $cart_item_id,
"pid" => $pid,
"name" => $pname,
"qty" => $itemQty,
"price_table_id" => $pt_id,
"paperType" => $paper,
"backCharges" => $backPrice,
"paperCharges" => $paperPrice,
"isBack" => $isBack,
"pricePerPiece" => $pricePerPiece,
"basePrice" => $basePrice,
"totalPrice" => $itemPrice,
"allQty" => $allAvailableQty,
];
$request->session()->put('cart.items.' . $cart_item_id, $item);
return 'Success';
Blockquote
Are you getting only error 500 and nothing else? If so, enable debug so you can get better description of the error. Make sure your php.ini file is set up properly and also permissions are fine for your server folders (I always get problems with the storage folder).

PHP code that generates words to C,C++ code

I had to develop a mini program that generates words from the given letters and some rules. I did this in PHP and it works great, BUT: now I need this code translated to C or C++. I've tried to implement it, but I have some troubles with string arrays. Moreover, I'm not good in C, even C++.
Someone, please help me to implement this code. Will do smth for you if I can. Thank you.
Here is the code attached:
<?php
$val_n = array("S","D","R");
$val_t = array("a","b","c","d","f");
$reguli = array(
array("S" => "aS"),
array("S" => "bD"),
array("S" => "fR"),
array("D" => "cD"),
array("D" => "dR"),
array("R" => 'bR')
);
$rez = array();
$pas = array();
$parcurgere = array();
$parc_sf = array();
function generare($val_n, $reguli, $cuvint, $parcurgere)
{
global $rez;
global $pas;
global $parcurgere;
global $parc_sf;
if( strlen($cuvint) >= 6)
{
if( $cuvint[strlen($cuvint) -1] == 'R' )
{
$cuvint[strlen($cuvint) -1] = "f";
if( ! in_array($cuvint, $rez) )
{
$rez[] = $cuvint;
array_push($parc_sf,$cuvint[strlen($cuvint) -1] = "f");
array_push($pas,$parcurgere);
}
} else if( $cuvint[strlen($cuvint) -1] == 'D' )
{
$cuvint[strlen($cuvint) -1] = "d";
if( ! in_array($cuvint, $rez) )
{
$rez[] = $cuvint;
array_push($parc_sf,$cuvint[strlen($cuvint) -1] = "d");
array_push($pas,$parcurgere);
}
}
} else if( $cuvint[strlen($cuvint) -1] != 'f' || $cuvint[strlen($cuvint) -1] != 'd')
{
foreach($reguli as $reg)
{
if(isset($reg[substr($cuvint, -1)]))
{
$pasi = $reg[substr($cuvint, -1)];
array_push($parcurgere,$pasi);
$cuvint .= $reg[substr($cuvint, -1)];
//$cuvint[strlen($cuvint)-3] = '';
generare($val_n, $reguli, $cuvint, $parcurgere);
}
}
}
}
$cuvint = "S";
$pasi = '';
generare($vn, $reguli, $cuvint, $parcurgere);
?>
I would suggest to look at std::vector which represents arrays that can change in size.
For the associate arrays (array("S" => "aS")), you can look at std::map or std::unordered_map

Adding html to t() in Drupal 6 template.php?

Hi I am trying to add html to the "t('Older Posts')" and "t('Newer Posts')" Is this possible ? I can figure it out ????
I am in a Drupal 6 template.php file.
This is the code I am trying to add as html -
<span>Newer Posts</span>
<span>Older Posts</span>
I need to replace the above in these spots located in the full function below ?
t('Older Posts')
t('Newer Posts')
I want to create something like this
t('<span>Older Posts</span>')
t('<span>Newer Posts</span>')
Full Function
function theme_views_mini_pager($tags = array(), $limit = 10,
$element = 0, $parameters = array(), $quantity = 9) {
global $pager_page_array, $pager_total;
// Calculate various markers within this pager piece:
// Middle is used to "center" pages around the current page.
$pager_middle = ceil($quantity / 2);
// current is the page we are currently paged to
$pager_current = $pager_page_array[$element] + 1;
// max is the maximum page number
$pager_max = $pager_total[$element];
// End of marker calculations.
$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] :
t('Older Posts')), $limit, $element, 1, $parameters);
if (empty($li_previous)) {
$li_previous = " ";
}
$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('Newer Posts')),
$limit,$element, 1, $parameters);
if (empty($li_next)) {
$li_next = " ";
}
if ($pager_total[$element] > 5) {
$items[] = array(
'class' => 'action back pager-previous',
'data' => $li_previous,
);
$items[] = array(
'class' => 'action pager-next',
'data' => $li_next,
);
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}
I am trying to figure out if this is possible I have tried many things and nothing has worked yet.
You can use
$link = '<span>' . t('Older Posts') . '</span>';
OR
$link = t('!link_startOlder Posts!link_end', array(
'!link_start' => '<a href="" class="action back"><span>',
'!link_end' => '</span></a>',
));

replace default image path with custome image path

All i really want to do is replace google's path with mine.
//code from module
$today = &$handler->current_conditions;
$condition = (string) $today->condition->attributes()->data;
$unit = google_weather_get_unit($convert_to);
$icon_src = (string) $today->icon->attributes()->data;
$content['current'] = array(
'temp' => $convert_to == 'SI' ? (string) $today->temp_c->attributes()->data . $unit : (string) $today->temp_f->attributes()->data . $unit,
'humidity' => (string) $today->humidity->attributes()->data,
'icon' => theme('image', 'http://www.google.com' . $icon_src, $condition, $condition, NULL, FALSE),
'condition' => $condition,
'wind_condition' => (string) $today->wind_condition->attributes()->data,
'custompath'=> $icon_src,
);
//code from tpl.php
<div class="weather-icon float-left">
// <?php print $content['current']['icon']; ?>
<?php print $base_url; ?>
<?php print $content['current']['custompath']; ?>
</div>
can't you just use a str_replace? For example if it now says http://www.google.com/images/icon.png and you need http://www.myhost.com/images/icon.png:
<?php print str_replace("www.google.com", "www.myhost.com", $content['current']['icon']); ?>

mysqli_query insert and update within array not working

Hey everyone I am trying to run two insert statements and than finally run an update statement within a php array but it seems not to be working correctly. I realize this code has some problems for instance escaping html data before inserting it into the database isn't ideal however i will fix that later the only thing I am concerned about is the insert and update statements. The following is the code I am using:
This is the job data array being built.
if(empty($_POST) === false && empty($errors) === true){
date_default_timezone_set('America/Denver');
$datetime =date("Y-m-d H:i:s");
$submissionId = rand(10000,99999);
$req_data = array(
'itemId' => $i_san,
'itemName' => $_POST['itemName'],
'submissionId' => $submissionId,
'username' => $_SESSION['username'],
'email' => $_SESSION['email'],
'subDate' => $datetime,
'wistiaId' => $_SESSION['wistiaId']
);
add_DCRequests($req_data);//INSERT INTO `DCrequests`
// === Sanatize inputs === //
$text_1_raw = $_POST['textOne'];
$text_1_noQuotes = str_replace('"',"'",$text_1_raw);
//$text_one = utf8_encode("Ñ");
$text_one = htmlentities(trim($text_1_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_2_raw = $_POST['textTwo'];
$text_2_noQuotes = str_replace('"',"'",$text_2_raw);
$text_two = htmlentities(trim($text_2_noQuotes) , ENT_QUOTES , 'UTF-8' );
$text_3_raw = $_POST['textThree'];
$text_3_noQuotes = str_replace('"',"'",$text_3_raw);
$text_three = htmlentities(trim($text_3_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_4_raw = $_POST['textFour'];
$text_4_noQuotes = str_replace('"',"'",$text_4_raw);
$text_four = htmlentities(trim($text_4_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_5_raw = $_POST['textFive'];
$text_5_noQuotes = str_replace('"',"'",$text_5_raw);
$text_five = htmlentities(trim($text_5_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_6_raw = $_POST['textSix'];
$text_6_noQuotes = str_replace('"',"'",$text_6_raw);
$text_six = htmlentities(trim($text_6_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_7_raw = $_POST['textSeven'];
$text_7_noQuotes = str_replace('"',"'",$text_7_raw);
$text_seven = htmlentities(trim($text_7_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_8_raw = $_POST['textEight'];
$text_8_noQuotes = str_replace('"',"'",$text_8_raw);
$text_eight = htmlentities(trim($text_8_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_9_raw = $_POST['textNine'];
$text_9_noQuotes = str_replace('"',"'",$text_9_raw);
$text_nine = htmlentities(trim($text_9_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_10_raw = $_POST['textTen'];
$text_10_noQuotes = str_replace('"',"'",$text_10_raw);
$text_ten = htmlentities(trim($text_10_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_11_raw = $_POST['textEleven'];
$text_11_noQuotes = str_replace('"',"'",$text_11_raw);
$text_eleven = htmlentities(trim($text_11_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_12_raw = $_POST['textTwelve'];
$text_12_noQuotes = str_replace('"',"'",$text_12_raw);
$text_twelve = htmlentities(trim($text_12_noQuotes) , ENT_QUOTES , 'UTF-8');
$aep = escape_data($_POST['aep']);
$output = escape_data($_POST['output']) . "_" . $_POST['subId'];
$output_scrub = preg_replace('/[^A-Za-z0-9\-_]/', "", $output);
$rendStatus = "ready";
//parse out 3 items from POST target (display shape matrix | disp w | disp h)
$item = escape_data($_POST['target']);
$get_target_w_h = explode('|', $item);
$targ = escape_data($get_target_w_h[0]);
$w = escape_data($get_target_w_h[1]);
$h = escape_data($get_target_w_h[2]);
$matrix = $w ."x". $h;
$BGColor = escape_data($_POST['hex']);
$bg_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $BGColor);
$c1 = escape_data($_POST['hex2']);
$c1_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $c1);
$c2 = escape_data($_POST['hex3']);
$c2_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $c2);
$c3 = escape_data($_POST['hex4']);
$c3_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $c3);
// if user is banner attach value = 2
if($_SESSION['userLevel'] == 5){$attach = 2;}else{$attach = 0;}
$show = escape_data($_POST['hide']);
if($show === '1'){
$show_1_val = '{{on}}';
$show_2_val = '{{off}}';
$show_3_val = '{{off}}';
}elseif($show === '2'){
$show_1_val = '{{off}}';
$show_2_val = '{{on}}';
$show_3_val = '{{off}}';
}elseif($show === '3'){
$show_1_val = '{{off}}';
$show_2_val = '{{off}}';
$show_3_val = '{{on}}';
}
$show1_scrub = preg_replace('/[^a-z\{}]/', "", $show1);
$show2 = escape_data($_POST['HideShowLayer2']);
$show2_scrub = preg_replace('/[^a-z\{}]/', "", $show2);
$show3 = escape_data($_POST['HideShowLayer3']);
$show3_scrub = preg_replace('/[^a-z\{}]/', "", $show3);
$still = escape_data($_POST['HideShowLayer1']);
$stillFrame = preg_replace('/[^0-9\.{}]/', "", $custStillFrame);
if($target_file1 != ""){
$image1 = "https://www.test.com/ce/". escape_data($target_file1);}
else{
$image1 = "";
}
if($target_file2 != ""){
$image2 = "https://www.test.com/ce/". escape_data($target_file2);}
else{
$image2 = "";
}
if($target_file3 != ""){
$image3 = "https://www.test.com/ce/". escape_data($target_file3);}
else{
$image3 = "";
}
$completion_date="";
$DCjobsFileId="";
$itemName = escape_data($_POST['itemName']);
$estimatedTime = $currentRendTotal + $custEstRenderTime;
$mydate = date('m/d/Y');
// === Data to insert into the table === //
$job_data = array(
//'bannerToken' => $bannerToken,
'attach' => $attach,
'full-date' => $mydate,
'aep' => $aep,
'target' => $targ,
'output' => $output_scrub,
'itemName' => $itemName,
'render-status' => $rendStatus,
'est_render_time' => $_POST['renderEst'],
'frameNumber' => $stillFrame,
'CustomerName' => $_SESSION['first_name'],
'CustomerEmail' => $_SESSION['email'],
'CustomerKey' => $_SESSION['wistiaId'],
'submissionDate' => $datetime,
'submissionId' => $_POST['subId'],
'itemId' => $custItemId,
'matrix' => $matrix,
'fileformat' => $_POST['format'],
'BGColor' => $bg_scrub,
'ColorOne' => $c1_scrub,
'ColorTwo' => $c2_scrub,
'ColorThree' => $c3_scrub,
'Text-One' => $text_one,
'Text-Two' => $text_two,
'Text-Three' => $text_three,
'Text-Four' => $text_four,
'Text-Five' => $text_five,
'Text-Six' => $text_six,
'Text-Seven' => $text_seven,
'Text-Eight' => $text_eight,
'Text-Nine' => $text_nine,
'Text-Ten' => $text_ten,
'Text-Eleven' => $text_eleven,
'Text-Twelve' => $text_twelve,
'HideShowOne' => $show_1_val,
'HideShowTwo' => $show_2_val,
'HideShowThree' => $show_3_val,
'ImageUploadOne' => $image1,
'ImageUploadTwo' => $image2,
'ImageUploadThree' => $image3,
'completion_date' => "CRAP",
'DCjobsFileId' => "CRAP"
);
add_jobs($job_data);//"INSERT INTO `DCjobs` and INSERT INTO `DCjobsArchive`
header('Content-Type: text/html; charset=utf-8');
header('Location: https://www.test.com/ce/thanks.php?est='.$estimatedTime);
exit();
}elseif(empty($errors) === false){
$reportErrors = "<br /><br /><br />Oops, the following errors occured: <br />" . $errors . "<br /><br /> Please click here to try again. <br /><br />";
}
?>
This is the function that inserts and updates the data from the jobdata array
function add_jobs($job_data){
global $db_conx;
array_walk($job_data, 'array_sanitize');
$jobfields = '`' . implode('`, `', array_keys($job_data)) . '`';
$jobdata = '\'' . implode('\', \'', $job_data) . '\'';
mysqli_query($db_conx, "INSERT INTO `DCjobs` ($jobfields) VALUES ($jobdata)");
mysqli_query($db_conx, "INSERT INTO `DCjobsArchive` ($jobfields) VALUES ($jobdata)");
$selectmaxdcjobsid="SELECT FileRowID, submissionDate FROM DCjobs WHERE submissionDate=(SELECT MAX(submissionDate) FROM DCjobs)";
mysqli_query($db_conx, $selectmaxdcjobsid);
while($row=mysqli_fetch_assoc($selectmaxdcjobsid)){
$maxdcjobsfileid=$row['FileRowID'];
$maxdcjobsubdate=$row['submissionDate'];
}
$selectarchiveid="select submissionId, submissionDate from DCjobsArchive where submissionDate='$maxdcjobsubdate'";
while($row=mysqli_fetch_assoc($selectarchiveid)){
$archivesubmissionid=$row['submissionId'];
$archivesubmissiondate=$row['submissionDate'];
}
$update="UPDATE DCjobsArchive SET DCjobsFileId='$maxdcjobsfileid' WHERE submissionId='$archivesubmissionid'";
mysqli_query($db_conx, $update);
}
It looks like you're trying to get the IDs assigned to the rows that you just inserted, so you can fill in a foreign key. You can do that using the MySQL built-in function LAST_INSERT_ID.
function add_jobs($job_data){
global $db_conx;
array_walk($job_data, 'array_sanitize');
mysqli_query($db_conx, "INSERT INTO `DCjobs` ($jobfields) VALUES ($jobdata)");
mysqli_query($db_conx, "INSERT INTO `DCjobsArchive` (DCjobsFileId, $jobfields) VALUES (LAST_INSERT_ID(), $jobdata)");
}

Categories