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.
Related
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";
I would like assign a user to a group with API REST.
But it doesn't work.
I use POST /groups/:id/users.:format syntax (see Rest Groups)
User with this id exists in redmine and group too.
In redmine log I can see:
Processing by GroupsController#add_users as XML
Parameters: {"group"=>{"user_id"=>"34"}, "key"=>"81aa228c55ac5cfe4264a566ef67ac27702da8eb", "id"=>"5"}
Current user: admin (id=1)
Rendering common/error_messages.api.rsb
Rendered common/error_messages.api.rsb (0.1ms)
Completed 422 Unprocessable Entity in 4ms (Views: 0.4ms | ActiveRecord: 1.3ms)
And in API's response:
Code Error :422
Message : User is invalid
In request body : id of user
I use ActiveResouce for REST API.
$method = 'users'
$options = array('user_id' => user's id to add)
/**
* Posts to a specified custom method on the current object via:
*
* POST /collection/id/method.xml
*/
function post ($method, $options = array (), $start_tag = false) {
$req = $this->site . $this->element_name_plural;
if ($this->_data['id']) {
$req .= '/' . $this->_data['id'];
}
$req .= '/' . $method . '.xml';
return $this->_send_and_receive ($req, 'POST', $options, $start_tag);
}
And this function for send request and parse the response :
/**
* Build the request, call _fetch() and parse the results.
*/
function _send_and_receive ($url, $method, $data = array (), $start_tag = false) {
$params = '';
$el = $start_tag ? $start_tag : $this->element_name; // Singular this time
if ($this->request_format == 'url') {
foreach ($data as $k => $v) {
if ($k != 'id' && $k != 'created-at' && $k != 'updated-at') {
$params .= '&' . $el . '[' . str_replace ('-', '_', $k) . ']=' . rawurlencode ($v);
}
}
$params = substr ($params, 1);
} elseif ($this->request_format == 'xml') {
$params = '<?xml version="1.0" encoding="UTF-8"?><' . $el . ">\n";
foreach ($data as $k => $v) {
if ($k != 'id' && $k != 'created-at' && $k != 'updated-at') {
$params .= $this->_build_xml ($k, $v);
}
}
$params .= '</' . $el . '>';
}
if ($this->extra_params !== false) {
if(strpos($url, '?'))
{
$url = $url .'&'.$this->extra_params;
}
else
{
$url = $url .'?'.$this->extra_params;
}
}
$this->request_body = $params;
$this->request_uri = $url;
$this->request_method = $method;
$res = $this->_fetch ($url, $method, $params);
if ($res === false) {
return $this;
}
// Keep splitting off any top headers until we get to the (XML) body:
while (strpos($res, "HTTP/") === 0) {
list ($headers, $res) = explode ("\r\n\r\n", $res, 2);
$this->response_headers = $headers;
$this->response_body = $res;
if (preg_match ('/HTTP\/[0-9]\.[0-9] ([0-9]+)/', $headers, $regs)) {
$this->response_code = $regs[1];
} else {
$this->response_code = false;
}
if (! $res) {
return $this;
} elseif ($res == ' ') {
$this->error = 'Empty reply';
return $this;
}
}
// parse XML response
$xml = new SimpleXMLElement ($res);
// normalize xml element name in case rails ressource contains an underscore
if (str_replace ('-', '_', $xml->getName ()) == $this->element_name_plural) {
// multiple
$res = array ();
$cls = get_class ($this);
foreach ($xml->children () as $child) {
$obj = new $cls;
foreach ((array) $child as $k => $v) {
$k = str_replace ('-', '_', $k);
if (isset ($v['nil']) && $v['nil'] == 'true') {
continue;
} else {
$obj->_data[$k] = $v;
}
}
$res[] = $obj;
}
return $res;
} elseif ($xml->getName () == 'errors') {
// parse error message
$this->error = $xml->error;
$this->errno = $this->response_code;
return false;
}
foreach ((array) $xml as $k => $v) {
$k = str_replace ('-', '_', $k);
if (isset ($v['nil']) && $v['nil'] == 'true') {
continue;
} else {
$this->_data[$k] = $v;
}
}
return $this;
}
Thank you
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) {
// ...
}
I making a plugin for wordpress, but i have problem with allowed memory size on my server, it is 128, they dont allow me to increase memory at run time.
my plugin have function to export user datas to csv and email to user. i getting fetal error on this wordpress, functions.php line 252
is there efficient way to optimize this below function to prevent getting error
thank you
function is_serialized( $data ) {
// if it isn't a string, it isn't serialized
if ( ! is_string( $data ) )
return false;
$data = trim( $data );
if ( 'N;' == $data )
return true;
$length = strlen( $data );
if ( $length < 4 )
return false;
if ( ':' !== $data[1] )
return false;
$lastc = $data[$length-1];
if ( ';' !== $lastc && '}' !== $lastc )
return false;
$token = $data[0];
switch ( $token ) {
case 's' :
if ( '"' !== $data[$length-2] )
return false;
case 'a' :
case 'O' :
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b' :
case 'i' :
case 'd' :
return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
}
return false;
}
my function - fileds are dynamic getting from admin panel
$outFile = '';
$blogusers = get_users();
// retrieve the current options
$spueIntervall = get_option('spue_intervall');
//fileds are dynamic
$spueSeperator = get_option('spue_seperator');
$spueFields = get_option('spue_fields');
// Check if the functions is already loaded
if (!function_exists('get_userdata'))
require_once (ABSPATH . 'wp-includes/pluggable.php');
// Setup the top-line of the file
foreach ($spueFields AS $fieldKey => $fieldValue)
{
if ($fieldValue == 1)
{
$outFile .= $fieldKey . $spueSeperator;
}
}
$outFile .= "\n";
// Loop to all users
foreach ($blogusers as $user)
{
// Get the userdate
$user_info = get_userdata($user->ID);
// Only output the needed data
foreach ($spueFields AS $fieldKey => $fieldValue)
{
if ($fieldValue == 1)
{
$outFile .= '"' . $user_info->{$fieldKey} . '"' . $spueSeperator;
}
}
$outFile .= "\n";
}
// Save
file_put_contents( dirname(__FILE__) . '\spue-export.csv', utf8_encode($outFile));
got it
foreach ( $blogusers as $user ) {
$data = array();
foreach ($spueFields AS $fieldKey => $fieldValue) {
if ($fieldValue == 1)
{
$value = isset( $user->{$fieldKey} ) ? $user->{$fieldKey} : '';
$value = is_array( $value ) ? serialize( $value ) : $value;
$data[] = '"' . str_replace( '"', '""', $value ) . '"';
$outFile.=implode( ',', $data ) . "\n";
}
I have a list of files in a directory in the format of YearMonthDay Time as below
20080508-120801suggestions.sql
20090508-120737categories.sql
20100508-120737articlelikes.sql
20110508-120737article.sql
20120508-120737comments.sql
20120508-120737loginusers.sql
20120508-120737popsearch.sql
20120508-120737suggestions.sql
20120508-120801article.sql
I want my PHP to display one item for the years then when you expand that it will then show you one item for the months then again one item for the day then in there all available backups for that day.
I have the first bit done where by it lists all the unique years and have been staring at the code for too long to know where to go next.
I am passing the variable year in to the URL so can pull that down as part of the code as required.
if ($handle = opendir($_SERVER['DOCUMENT_ROOT'] . 'sqlbackup/'))
{
while (false !== ($entry = readdir($handle)))
{
$isYearfound = 'false';
//$dirlist = array();
if (($entry != ".") AND ($entry != ".."))
{
foreach ($dirarray as $dirarrayyear)
{
if (substr($entry, 0, 4) == $dirarrayyear)
{
$isYearfound = 'true';
}
}
if ($isYearfound == 'false')
{
$dirarray[] = substr($entry, 0, 4);
Print "<a href='myknowledge.php?mnpage=managedb&date=" . substr($entry, 0, 4) . "'>" . substr($entry, 0, 4) . "</a><br/>";
}
//Print $entry . "<br/>";
}
}
closedir($handle);
}
So the first part looks fine. But you probably want to pass the year and month in the URL so that the code then compares the first 6 characters of the filename, and then for those URLs generated it would pass the full 8 characters.
first pass date=2008
second pass date=200805
third pass date=20080501
hello Form what i see all the month are 05 so you would not get disred result ... i change the dates in my demo and i got this
$dir = new DirectoryIterator('PATH_TO_SQL_DIR');
$list = array();
foreach($dir as $file)
{
if($file->isDot())
continue;
list($prifix,$surfix) = explode("-", $file->getFilename(),2);
$date = DateTime::createFromFormat("Ymd", $prifix);
$year = $date->format("Y");
$month = $date->format("M");
if(!isset($list[$year]))
{
$list[$year] = array();
}
if(!in_array($month, $list[$year]))
{
$list[$year][] = $month;
}
}
echo "<pre>" ;
print_r($list);
Output
Array
(
[2008] => Array
(
[0] => May
[1] => Dec
)
[2009] => Array
(
[0] => May
)
[2010] => Array
(
[0] => May
)
[2011] => Array
(
[0] => May
)
[2012] => Array
(
[0] => Jan
[1] => Feb
[2] => May
[3] => Dec
)
)
You can not use this to build any kind of links you want ...
I have created a script for you that my help.
It is not recursive but I think it does what you want and you don't need to make recursive at all.
please change directory paths/script names, etc to yours and it will work for you.
$dir = scandir('myfiles');
$prevyear=0;
$prevmonth=0;
$prevday=0;
foreach ($dir as $file) {
if ($file!='.' && $file!='..') {
if (isset($_GET["year"]) && isset($_GET["month"]) && isset($_GET["day"])) { //if all three is set show file
if (preg_match('/^'.$_GET["year"].$_GET["month"].$_GET["day"].'/',$file,$match)) {
echo ''.$file.'<br />';
}
} else if (isset($_GET["year"]) && isset($_GET["month"])) { //if only year and month set show days
if (preg_match('/^'.$_GET["year"].$_GET["month"].'/',$file,$match)) {
$day = preg_replace(array('/^\d{6}/','/\-.*?$/'),'',$file);
if ($day!=$prevday) {
echo '' . $day . '<br />';
$prevday=$day;
}
}
} else if (isset($_GET["year"])) { //if only year set show months
if (preg_match('/^'.$_GET["year"].'/',$file,$match)) {
$month = preg_replace(array('/^\d{4}/','/\d{2}\-.*?$/'),'',$file);
if ($month!=$prevmonth) {
echo '' . $month . '<br />';
$prevmonth=$month;
}
}
} else { //if nothing set show years
$year = preg_replace('/\d{4}\-.*?$/','',$file);
if ($year!=$prevyear) {
echo '' . $year . '<br />';
$prevyear=$year;
}
}
}
}
Thanks very much to Baba for all the help. This is the code I used in the end to resolve the issue.
$dir = new DirectoryIterator($_SERVER['DOCUMENT_ROOT'] . 'sqlbackup/');
$list = array();
foreach($dir as $file)
{
if($file->isDot())
continue;
list($prifix,$surfix) = explode("-", $file->getFilename(),2);
$date = DateTime::createFromFormat("Ymd", $prifix);
$year = $date->format("Y");
$month = $date->format("m");
$day = $date->format("d");
if(!isset($list[$year]))
{
$list[$year] = array();
}
if(!in_array($day, $list[$year][$month][$day]))
{
$list[$year][$month][$day] = $day;
}
}
echo "<pre>" ;
foreach (array_keys($list) as $value)
{
Print "<a href='myknowledge.php?mnpage=managedb&date=" . $value . "'>" . $value . "</a><br/>";
if ($value == substr($_GET['date'], 0, 4))
{
foreach (array_keys($list[$value]) as $value2)
{
Print " <a href='myknowledge.php?mnpage=managedb&date=" . $value . $value2 ."'>" . $value2 . "</a></br/>";
}
}
}
//print_r($list);