I have a variable ($statement) that will store dynamic content like the below:
($row[Gender] == "Female") && ($row[Grade] == "A" || $row[Grade] == "B" || $row[Grade] == "C1") && ($row[Race] == "African" || $row[Race] == "Coloured" || $row[Race] == "Indian" || $row[Race] == "White")
I want to then use this $statement in a if condition like so: if ($statment) {do logic here...}. This is used to match values in an array held in $row (e.g. $row[Gender] which has the value "Male").
Is this achievable and what's the best way to do it?
The whole method() is:
public function ApplyRuleset ($activeOpportunity, $step, $companyId, $projectId, $phaseId) {
// Get global vars
global $conn;
// Get non declined employees for this opportunity only
$getAllCandidates = $this->GetTalentPool ("normal", $step, $activeOpportunity[0]['oppID'], $companyId, $projectId, $phaseId);
// Get column slices
$columnSlices = GetSlices ($conn, $companyId, $projectId, $phaseId, 0);
// Split ruleset into manageable parts
$columnSets = explode (" AND ", $activeOpportunity[0]['rule']);
echo "<pre>";
// Check that we have all that we need
if (is_array ($getAllCandidates) && is_array ($columnSlices) && is_array ($columnSets)) {
// Get selected talent pool
foreach ($getAllCandidates as $row) {
// Format business rules
foreach ($columnSlices as $sliceValue) {
// Get the slices to match which facets were selected
$qualifiedName = preg_replace ('/\s+/', "", $sliceValue['facet']);
// Loop through column match
foreach ($columnSets as $set) {
// Get olumn match
$ruleMatch = explode (" -> ", $set);
$columnName = $ruleMatch[0];
$options = explode (",", $ruleMatch[1]);
// Match rule
for ($i = 0; $i < count ($options); $i++) {
// Write conditional statement
$statement .= '("$row[' . $columnName . ']" == "' . $options[$i] . '"';
$statement .= (count ($options) > 1 && $options[$i] !== end ($options)) ? " || " : ") && (";
}
}
break;
}
// Finalise statement
$editStatement = preg_replace ("/ && \($/", "", $statement);
$editStatement = preg_replace ("/ \(/", " ", $editStatement);
$editStatement = preg_replace ('/"\$/', "$", $editStatement);
$finaliseStatement = preg_replace ('/\]"/', "]", $editStatement);
// Do record match
if ($finaliseStatement) {
// Record matches, load into match array
$this->rulesetMatch[] = $row;
// Set required vars
$_REQUEST['selected'] = (array) $row[candidateId];
$_REQUEST['opportunityID'] = $activeOpportunity[0]['oppID'];
$_REQUEST['step'] = $step;
// Insert these records for round 1
//$this->AddCandidatesToOpportunity ();
}
}
}
// Return all the rows that matched and dedupe
return array_map ("unserialize", array_unique (array_map ("serialize", $this->rulesetMatch)));
}
You can use the result of the if in a variable called $statement like
$statement = (($row[Gender] == "Female") && ($row[Grade] == "A" || $row[Grade] == "B" || $row[Grade] == "C1") && ($row[Race] == "African" || $row[Race] == "Coloured" || $row[Race] == "Indian" || $row[Race] == "White"));
and then you can use this result in if statement as you wish
if ($statement === true) {
// ...
}
Related
I'm creating a function that has to check for several inputs and create a variable that I use to call a SQL query, the problem I'm facing is that I want to change a variable so that I don't use the SELECT call every time, but instead the AND call. How does one construct such a function? This is what I currently have.
if ($_GET['filtering2'] != "" || $_GET['filtering3'] != "" || $_GET['filtering4'] != "" || $_GET['filtering5'] != "" || $_GET['filtering6'] != "" || $_GET['filtering7'] != "" || $_GET['filtering7'] != "") {
function searchByColumn($values, $columnName)
{
$string = implode(" OR season LIKE ", $values);
if ($firstTime = 2) {
return "SELECT * FROM shrubs2 WHERE season LIKE $string";
} else {
return " AND WHERE season LIKE $string";
}
}
$colNames = array("season"); // can add here more column names
foreach ($colNames as $colName) {
$str .= searchByColumn($array_name, $colName);
$firstTime = 3;
}
}
if ($_GET['filtering8'] != "" || $_GET['filtering9'] != "" || $_GET['filtering10'] != "" || $_GET['filtering11'] != "") {
function searchByColumn2($values, $columnName2)
{
$string2 = implode(" OR 日照 LIKE ", $values);
if ($firstTime = 2) {
return "SELECT * FROM shrubs2 WHERE 日照 LIKE $string2";
} else {
return " AND WHERE 日照 LIKE $string2";
}
}
$colNames2 = array("日照"); // can add here more column names
foreach ($colNames2 as $colName2) {
$str .= searchByColumn2($array_name2, $colName2);
$firstTime = 3;
}
}
I was trying to change the variable $firstTime, but it never resulted as I wished for it to do.
first edit:
if($_GET['filtering8'] != "" || $_GET['filtering9'] != "" || $_GET['filtering10'] != "" || $_GET['filtering11'] != "" ){
function searchByColumn2($values, $columnName2) {
$string2 = implode(" OR 日照 LIKE ", $values);
if($firstTime != 3){
return "SELECT * FROM shrubs2 WHERE 日照 LIKE $string2";
$firstTime = 3;
} else{
return " AND WHERE 日照 LIKE $string2";
}
}
$colNames2 = array("日照"); // can add here more column names
foreach($colNames2 as $colName2) {
$str .= searchByColumn2($array_name2, $colName2);
}
}
and of course I've added:
global $firstTime;
since the variable is global you need to define the global by adding
global $firstTime;
on first line of searchByColumn and searchByColumn2 function. it will refer to global variable $firstTime
I need to combine two or more array elements enclosed inside a double quotation mark...
Example:
- Before -
[
"Foo1",
"\"Foo2",
"Foo3",
"Foo4\"",
"Foo5"
]
-After -
[
"Foo1",
"\"Foo2 Foo3 Foo4\"",
"Foo5"
]
Below, $source and $result are the source and result respectively. I would use array_reduce()
$result = array_reduce($source, function($acc,$i) {
static $append = false; // static so value is remembered between iterations
if($append) $acc[count($acc)-1] .= " $i"; // Append to the last element
else $acc[] = $i; // Add a new element
// Set $append=true if item starts with ", $append=false if item ends with "
if(strpos($i,'"') === 0) $append = true;
elseif (strpos($i,'"') === strlen($i)-1) $append = false;
return $acc; // Value to be inserted as the $acc param in next iteration
}, []);
Live demo
function combine_inside_quotation($array)
{
if(!is_array($array) || 0 === ($array_lenght = count($array))) {
return [];
}
$i = 0;
$j = 0;
$output = [];
$inside_quote = false;
while($i < $array_lenght) {
if (false === $inside_quote && '"' === $array[$i][0]) {
$inside_quote = true;
$output[$j] = $array[$i];
}else if (true === $inside_quote && '"' === $array[$i][strlen($array[$i]) - 1]) {
$inside_quote = false;
$output[$j] .= ' ' . $array[$i];
$j++;
}else if (true === $inside_quote && '"' !== $array[$i][0] && '"' !== $array[$i][strlen($array[$i]) - 1]) {
$output[$j] .= ' ' . $array[$i];
} else {
$inside_quote = false;
$output[$j] = $array[$i];
$j++;
}
$i++;
}
return $output;
}
Try this function it gives the output you mentioned.
Live Demo
I am in the midst of writing a simple job board and I have the URL's filtering and working how I want, everything works - I just want to know if I can improve it, if there are any security concerns, and if it is horribly inefficient.
Take the following URL section - foo.com/in/london/at/google/do/design
I assign each section a variable and work out the location, company, and category.
Other use cases that work:
Switching the order - foo.com/at/google/in/london/do/design
Having less parameters - foo.com/in/london/at/google
My code to figure out all these variables is:
// Get the different possible page parameters
// Only allow alphanumeric, dashes, and commas
$regex = "[^a-zA-Z0-9,-]";
$a = isset($_GET["a"]) ? preg_replace("/".$regex."/", "", $_GET["a"]) : "";
$aa = isset($_GET["aa"]) ? preg_replace("/".$regex."/", "", $_GET["aa"]) : "";
$b = isset($_GET["b"]) ? preg_replace("/".$regex."/", "", $_GET["b"]) : "";
$bb = isset($_GET["bb"]) ? preg_replace("/".$regex."/", "", $_GET["bb"]) : "";
$c = isset($_GET["c"]) ? preg_replace("/".$regex."/", "", $_GET["c"]) : "";
$cc = isset($_GET["cc"]) ? preg_replace("/".$regex."/", "", $_GET["cc"]) : "";
if ($a == "in" && $aa != null) { $searchLocation = $aa; }
if ($b == "in" && $bb != null) { $searchLocation = $bb; }
if ($c == "in" && $cc != null) { $searchLocation = $cc; }
if ($a == "at" && $aa != null) { $searchCompany = $aa; }
if ($b == "at" && $bb != null) { $searchCompany = $bb; }
if ($c == "at" && $cc != null) { $searchCompany = $cc; }
if ($a == "do" && $aa != null) { $searchCategory = $aa; }
if ($b == "do" && $bb != null) { $searchCategory = $bb; }
if ($c == "do" && $cc != null) { $searchCategory = $cc; }
if ($a == "missinghtml") { $errorUrl = true; }
I'm looking at this thinking there must be a better to do this, and is this section secure?
Any thoughts on this are much appreciated. Like I say it works, but can it be better? Thanks :)
$start = true;
$new = "";
foreach($array as $val)
{
if($start = true && $val != " ")
{
$start = false;
$new .= strtoupper($val);
}
elseif($val == " ")
{
$new .= " ";
$start = true;
}
else
{
$new .= strtolower($val);
}
$start = false;
}
Basically what happens is $start NEVER becomes false AND everything becomes capitalized. So it looks like the first if IS running, but for some reason NEVER SETS $start to false.
I cannot stress it enough: use the yoda condition
if(true == $var)
or generally:
if(CONSTANT == $VARIABLE)
and not
if($VARIABLE == CONSTANT) //which you'd wrongly type as "="
PHP would have told you what went wrong in that case - no matter how tired you are.
Looking for this bug (it happens to the best of the best too) is frustrating.
Let the tool (PHP) be supportive to you, don't make it work against you.
That was on a more general note. As for your problem, it's doable with a one-liner:
<?php
$array = "hEllo woRlD";
var_dump(ucwords(strtolower($array)));
$start = true is an assignment, not a comparison. Use ==.
You're using a single equals in your test, which means "assignment". You probably meant == (equality), but in this case, with booleans, you don't need to compare at all:
$start = true;
$new = "";
foreach($array as $val)
{
if($start && $val != " ") // <-- remove the = true here
{
$start = false;
$new .= strtoupper($val);
}
elseif($val == " ")
{
$new .= " ";
$start = true;
}
else
{
$new .= strtolower($val);
}
$start = false;
}
Right now, it's getting interpreted as "Set $start to true && $val != " "" - definitely not what you intended.
$start = true && $val != " " means:
$start = (true && $val != " ")
$start = ($val != " ")
$start = !($val == " ") // $start is true except when $val is a single space.
I believe you meant $start == true.
Are you just trying to upper case the first character of every word? If so, look into ucwords.
I have an array from a $_GET say
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
for which i am using this while loop to create a string:
while (list($key, $value) = each($_GET)) {
$get_url .= $key . '=' . rawurlencode(stripslashes($value)) . '&';
}
Now if i get an array from $_GET say like:
Array
(
[0] => pid
[1] => gid
[2] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
)
then in this case what could be the possible changes be done to while loop so that I can avoid the result like this http://www.example.com/shopping_cart.php?0=pid&1=gid&2=Array in url when i use this to redirect it.
I want the url to display the values properly..not like "2=Array".. how can i do this?
EDIT
Thanks Folks for the help, but I cannot introduce new function neither I can replace the while loop with for loop, I would be very thankfull if you can help me in re-editing the given WHILE Loop...
EDIT 2
I am using header(location:$get_url) for redirecting to created url, is this the problem of display of "2=Array" in url?
EDIT 3
functions used to build query, NOTE: THESE FUNCTIONS ARE INBUILT FUNCTION OF osCommerce
I still changed one of it by introducing the foreach loop into it see below the use and function definition:
function tep_redirect($url) {
if ( (strstr($url, "\n") != false) || (strstr($url, "\r") != false) ) {
tep_redirect(tep_href_link(FILENAME_DEFAULT, '', 'NONSSL', false));
}
if ( (ENABLE_SSL == true) && (getenv('HTTPS') == 'on') ) { // We are loading an SSL page
if (substr($url, 0, strlen(HTTP_SERVER . DIR_WS_HTTP_CATALOG)) == HTTP_SERVER . DIR_WS_HTTP_CATALOG) { // NONSSL url
$url = HTTPS_SERVER . DIR_WS_HTTPS_CATALOG . substr($url, strlen(HTTP_SERVER . DIR_WS_HTTP_CATALOG)); // Change it to SSL
}
}
$url = str_replace("&", "&", $url);
header('Location: ' . $url);
tep_exit();
}
=========================
function tep_href_link($page = '', $parameters = '', $connection = 'NONSSL', $add_session_id = true, $search_engine_safe = true) {
global $request_type, $session_started, $SID, $spider_flag;
if (!tep_not_null($page)) {
die('</td></tr></table></td></tr></table><br><br><font color="#ff0000">' . TEP_HREF_LINK_ERROR1);
}
if ($connection == 'NONSSL') {
$link = HTTP_SERVER . DIR_WS_HTTP_CATALOG;
} elseif ($connection == 'SSL') {
if (ENABLE_SSL == true) {
$link = HTTPS_SERVER . DIR_WS_HTTPS_CATALOG;
} else {
$link = HTTP_SERVER . DIR_WS_HTTP_CATALOG;
}
} else {
die('</td></tr></table></td></tr></table><br><br><font color="#ff0000">' . TEP_HREF_LINK_ERROR2);
}
if (tep_not_null($parameters)) {
while ( (substr($parameters, -5) == '&') ) $parameters = substr($parameters, 0, strlen($parameters)-5);
$link .= $page . '?' . tep_output_string($parameters);
$separator = '&';
} else {
$link .= $page;
$separator = '?';
}
// if session is not started or requested not to add session, skip it
if ( ($add_session_id == true) && ($session_started == true) ){
// if cookies are not set and not forced, then add the session info incase the set cookie fails
if ( ! isset($_COOKIE[tep_session_name()]) && (SESSION_FORCE_COOKIE_USE == 'False') ) {
$_sid = tep_session_name() . '=' . tep_session_id();
// if we are chaning modes and cookie domains differ, we need to add the session info
} elseif ( HTTP_COOKIE_DOMAIN . HTTP_COOKIE_PATH != HTTPS_COOKIE_DOMAIN . HTTPS_COOKIE_PATH
&&
(
( $request_type == 'NONSSL' && $connection == 'SSL' && ENABLE_SSL == true )
||
( $request_type == 'SSL' && $connection == 'NONSSL' )
)
) {
$_sid = tep_session_name() . '=' . tep_session_id();
}
}
if (isset($_sid) && !$spider_flag) {
$link .= $separator . tep_output_string($_sid);
}
return $link;
}
===========================
function tep_get_all_get_paramtrs($exclude_array = '') {
global $HTTP_GET_VARS;
if (!is_array($exclude_array)) $exclude_array = array();
$get_url = '';
if (is_array($HTTP_GET_VARS) && (sizeof($HTTP_GET_VARS) > 0))
{
reset($HTTP_GET_VARS);
foreach($HTTP_GET_VARS as $key => $a)
{
if(is_array($a))
{
foreach($a as $k => $v)
{
$get_url[] = $key . '[]' . '=' . rawurlencode(stripslashes($v));
}
}
else
{
$get_url[] = $key . '=' . rawurlencode(stripslashes($a));
}
}
/* while (list($key, $value) = each($HTTP_GET_VARS))
{
if(!is_array($value))
{
if ( (strlen($value) > 0) && ($key != tep_session_name()) && ($key != 'error') && (!in_array($key, $exclude_array)) && ($key != 'x') && ($key != 'y') )
{
$get_url .= $key . '=' . rawurlencode(stripslashes($value));
}
}
else
{
if ( (strlen($value) > 0) && ($key != tep_session_name()) && ($key != 'error') && (!in_array($key, $exclude_array)) && ($key != 'x') && ($key != 'y') )
{
$get_url .= preg_replace('/#\d/','[]',http_build_query($value,$key.'#'));
}
/* while(list($key1, $value1) = each($value))
{
if ( (strlen($value1) > 0) && ($key1 != tep_session_name()) && ($key1 != 'error') && (!in_array($key1, $exclude_array)) && ($key1 != 'x') && ($key1 != 'y') )
{
$get_url .= $key1 . '=' . rawurlencode(stripslashes($value1));
}
}*/
/* }
}*/
$get_url .= '&';
}
return $get_url;
}
========================
tep_redirect(tep_href_link($goto, tep_get_all_get_paramtrs($parameters)));
here $parameters is an array with two values which doesnt have any resemblence with url display logic
did you consider using http_build_query() or http_build_url()?
If you want to create an url from a multi-dimensional array, you should use a recursion, or just the built-in php function, which results the same as the function I created http-build-query() (just as Maurice Kherlakian said). It's the easiest way for doing this.
A recursive function example:
function URLfromArray($array,$url = "")
{
foreach($array as $key => $val)
{
if(is_array($val))
{
$url = URLfromArray($val,$url);
}
else
{
$url .= $key."=".$val."&";
}
}
return $url;
}
You could check with is_array and use implode or just loop through the array if you want different keys such as 2_0, 2_1.
You can check if the value is an array, then recurse or iterate over it...
if (is_array($value)
{
// process this array
}
else
{
// normal path
$get_url .= $key . '=' . rawurlencode(stripslashes($value)) . '&';
}
http://php.net/manual/en/function.is-array.php
header() has nothing to do with your problem.
you just fail to build proper query string
And I wonder why your problem is still persists despite of all these http_build_query() you've been told already
You could use serialize to serialize the array into a single string and urlencode that resulting string, on the receiving end you would then use urldecode and unserialize.