I wrote a simple function (copied and adapted, more like it!) to make breadcrumb for one application. My folder structure is such that if some folders are ignored, the trail would still work. I have looked it for far too long with no progress ...
function breadCrumb(){
// folders to ignore
$filterFolders = array('360', 'files');
if($location = substr(dirname($_SERVER['PHP_SELF']), 1)){
$dirlist = explode('/', $location);
}else{
$dirlist = array();
}
/** update the array with non required folders **/
$filteredArr = array_diff_key($dirlist, array_flip($filterFolders));
$count = array_push($filteredArr, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'Home';
for($i = 0; $i < $count; $i++){
echo ' » '.ucfirst($filteredArr[$i]).'';
}
}
Thanks in advance, any help would be much appreciated!
I don't see any use of array_filter in your code, contrary to what's suggested by the question title. However, You should be running the difference function on values, not on keys (because you didn't specify any) in this case.
Hence
$filteredArr = array_diff_key($dirlist, array_flip($filterFolders));
^
Should be
$filteredArr = array_diff($dirlist,$filterFolders); // you don't even ve to flip
For example
$filterFolders = array('360', 'files');
What would you expect those keys to be? they are 0 for the value 360 and 1 for the value 'files', so checking the difference of keys won't do what's expected.
Related
I'm using below function to redirect a specific url to a specific php script file:
add_action('wp', function() {
if ( trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/') === 'pagename' ) {
include(locate_template('give_some.php'));
exit();
}});
it works only for the specified url and i want to make it work for multiple urls. Suppose a file urls.txt contain numbers of url and for which above code have to be triggered. Any idea how to do this?
I’m a long-time WordPress developer, and one of the best responses to a WordPress problem is “that’s not a WordPress problem, just simple PHP (or JavaScript)” one. That’s a really good thing because it makes it really easy to talk about.
Your problem, as I understand it, is that you want to compare the current URL to a “file” of possible paths. You’ve got the WordPress equivalent of “current URL”, so I’ll take that for granted, and I’ll also assume you can take a file and convert it into an array. But once you do that, you are parsing a URL (which you already did) and seeing if it is in the array:
$url = 'https://www.example.com/pagename?a=b&c=d';
$paths = [
'gerp',
'pagename',
'cheese',
];
$path = trim(parse_url($url, PHP_URL_PATH), '/');
if ( in_array($path, $paths )) {
echo 'yes';
} else {
echo 'no';
}
Demo: https://3v4l.org/NOmpk
You can use different hook request. Which allow you to manipulate request.
add_filter( 'request', function( $request ){});
My simple example ( not tested ).
add_filter( 'request', function( $request ){
$data = file_get_contents("database.txt"); //read the file
$rows = explode("\n", $data); //create array separate by new line
$rows = array_map("trim", $rows); // for removing any unwanted space
$rowCount = count($rows); // Count your database rows
for ($i=0; $i < $rows ; $i++) {
if( isset( $request['pagename'] ) && $rows[$i] == $request['pagename'] ){
include(locate_template('give_some.php'));
}
}
return $request;
});
My advice, don't use .txt files, save your data into database, and then use it, or create wp_option field, and manage from Settings page.
I'm working on a project, and it has a bunch of variables for some links that I define. But I want to add a string at the end of those variable only if I got some GET parameters. The thing is I don't want to have another huge amount of variables and I want to have the same name for the variables. After some research, I came with this operator .= which is perfect for me. I also made a for loop it works well for the variable value, but I don't have the same name.
Here is what I got:
$homeLink = $wURL.'government/'.$job.'/';
$databaseLink = $wURL.'government/'.$job.'/search/database';
$overviewLink = $wURL.'government/'.$job.'/overview';
// Other variables
if (!isset($_SESSION['steamid']) && isset($_GET['uID']) && isset($_GET['uToken'])) {
// redefine the variables like this:
$homeLink .= '?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP'];
/*
OUTPUT: $wURL.'government/'.$job.'/'.'?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP']
*/
// The for loop:
$arr = array($homeLink,$databaseLink,$overviewLink);
$nb = count($arr);
for ($i=0; $i < $nb ; $i++) {
$arr[$i] .= '?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP'];
echo $arr[$i]."<br>";
// have the same output that above but I have to call my variables with $arr[<a number>];
}
}
The thing is I don't want to have another huge amount of variables and I want to have the same name for the variables, any ideas on how I can proceed?
First, your 2 last links are actually both based on the first one, $homeLink:
$homeLink = $wURL.'government/'.$job.'/';
$databaseLink = $homeLink.'search/database';
$overviewLink = $homeLink.'overview';
then why not build the parameter string and then append it?
$homeLink = $wURL.'government/'.$job.'/'
$paramString = '';
if (!isset($_SESSION['steamid']) && isset($_GET['uID']) && isset($_GET['uToken'])) {
$paramString = '?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP'];
}
$databaseLink = $homeLink.'search/database'.$paramString;
$overviewLink = $homeLink.'overview'.$paramString;
$homeLink .= $paramString;
I don't get why you want to store your URLs in an array, these are different URLs, thus to be used in different contexts, having all of them in one array is of course possible but doesn't bring any value, in my opinion.
To conclude, if $userinfoVlife['websiteMDP'] contains a readable password, you definitely have a problem in your application architecture: it's very bad practice to handle raw passwords and it's even worse to pass it in the URL.
I'm working on a 'thought' function for a game i'm working on -- it pulls random strings from an XML file, combines them and makes them 'funny'. However, i'm running into a small issue in that the same couple of items keep getting selected each time.
The two functions I am using are
function randRoller($number)
{
mt_srand((microtime()*time())/3.145);
$x = [];
for($i = 0; $i < 100; $i++)
{
#$x = mt_rand(0,$number);
}
return mt_rand(0,$number);
}
/* RETRIEVE ALL RELEVANT DATA FROM THE XML FILE */
function retrieveFromXML($node)
{
$node = strtolower($node);
$output = [];
$n = substr($node,0,4);
#echo $node;
foreach($this->xml->$node->$n as $data)
{
$output[] = $data->attributes();
}
$count = count($output)-1;
$number = $this->randRoller($count);
return $output[$number];
}
Granted, the "randRoller" function is sorta defunct now because the orginal version I had (Which 'rolled' ten numbers from the count, and then selected the one which got the most number of dice) didn't work as planned.
I've tried everything i can think of to get better results && have googled my brains out to fix it. but still am getting the same repetitive results.
Don't use mt_srand() unless you know what you are doing, since it is called automatically. See the note on http://php.net/manual/en/function.mt-srand.php:
Note: There is no need to seed the random number generator with srand() or mt_srand() as this is done automatically.
Remove (all) the mt_srand() call(s).
I have a pretty complicated array operation, or at least it is complicated for me. Lets say I got such kind of array
$myArr['url_1']['linktypes']['follow'] = 10;
$myArr['url_1']['linktypes']['nofollow'] = 20;
$myArr['url_1']['linktypes']['other'] = 30;
$myArr['url_2']['linktypes']['follow'] = 40;
$myArr['url_2']['linktypes']['nofollow'] = 50;
$myArr['url_2']['linktypes']['other'] = 60;
$myArr['url_3']['linktypes']['follow'] = 70;
$myArr['url_3']['linktypes']['nofollow'] = 80;
$myArr['url_3']['linktypes']['other'] = 90;
and simply (!) I need to get following result
array(
array("id"=>1,"metric"=>'follow','url_1'=>10,'url_2'=>40,'url_3'=>70),
array("id"=>2,"metric"=>'nofollow','url_1'=>20,'url_2'=>50,'url_3'=>80),
array("id"=>3,"metric"=>'other','url_1'=>30,'url_2'=>60,'url_3'=>90)
);
These array elements are created dynamicall from $myArr. I have tried many ways but I failed many times. Hopefully someone has a short, simple logic to solve this.
Thanks.
Edit: This one is my shortest try. I have many different ways but this code is a part of big code structure, example you see here is created to simplify the logic I need.
$linkStructure = array();
foreach($myArr as $links=>$value){
$counter = 0;
foreach($value['linktypes'] as $ltKey => $ltValue){
if($linkStructure[$counter]["id"] && $linkStructure[$counter]["metric"] == $ltKey){
$linkStructure[$counter][$links] = $ltValue;
}
else{
$linkStructure[$counter]["id"] = $counter;
$linkStructure[$counter]["metric"] = $ltKey;
$linkStructure[$counter][$links] = $ltValue;
}
}
}
I swear I tried how I can prove better I don't know. Don't torture please. If you have any idea just share, is it too much I'm asking for?
I can't explain this very well, so I'm just going to use code:
$fixedArr = array();
$idCount = 1;
foreach($myArr as $title=>$subArr)
foreach($subArr['linktypes'] as $metric=>$val) {
if(!array_key_exists($metric)) {
$fixedArr[$metric] = array();
$fixedArr[$metric]['id'] = $idCount;
$fixedArr[$metric]['metric'] = $metric;
$idCount += 1;
}
$fixedArr[$metric][$title] = $val;
}
That should do it.
But I should say that the comments are right, a better way to structure your array would be like this:
Array {
[url_*] => Array {
[metric] => someValue;
}
}
Basically the same way you have it originally, but with fewer dimensions. This is all that you need for the data you have provided.
self::$currentend = $cfp;
self::$currentend = &$cfp->next;
self::$basisend = $cfp;
self::$basisend = &$cfp->bp;
What does it do?
Found here.
UPDATE
My question is since
self::$currentend = $cfp;
self::$currentend = &$cfp->next;
always evaluates to
self::$currentend = &$cfp->next;
So why the extra line?
Your PHP code is a C->PHP port of the LEMON parser generator, which includes this code:
/* Add another configuration to the configuration list */
struct config *Configlist_add(rp,dot)
struct rule *rp; /* The rule */
int dot; /* Index into the RHS of the rule where the dot goes */
{
struct config *cfp, model;
assert( currentend!=0 );
model.rp = rp;
model.dot = dot;
cfp = Configtable_find(&model);
if( cfp==0 ){
cfp = newconfig();
cfp->rp = rp;
cfp->dot = dot;
cfp->fws = SetNew();
cfp->stp = 0;
cfp->fplp = cfp->bplp = 0;
cfp->next = 0;
cfp->bp = 0;
*currentend = cfp;
currentend = &cfp->next;
Configtable_insert(cfp);
}
return cfp;
}
It's in the PHP because it was in the original C. In the original C, it writes through the currentend pointer to replace the contents of whatever it is pointing at (memory allocated elsewhere, probably contains garbage), and then it updates the currentend pointer to point to the struct node pointed to by cfp->next (which is 0, here, which is why I think some other routine will allocate the memory for it later).
In other words, it appends the new struct rule to the end of a list of struct rules while maintaining a pointer to the "last entry". (Well, an entry beyond the end. Where the next last-entry will go, once it exists. All of which makes accessing the end-of-the-list an O(1) operation, superb for improving list-append operations.)
I have no idea what that is from, it looks weird, but I can explain:
self:: refers to the class of the current object/class.
$currentend & $basisend are variables storing variable names - that is, if the code were like this:
$currentend = bla1;
$currentend = bla2;
then it essentially evaluates to:
self::bla1 = $cfp;
self::bla1 =& $cfp->next;
self::bla2 = $cfp;
self::bla2 =& $cfp->bp;
So whatever the value behind $currentend & $basisend, they are refering to static variables within the current class.
The & is a reference operator. It basically means that you do not want to copy the variable, but "share" the variable referenced by both of the other variables. Actually, to assign a pointer to the variable.
Other than that, I have no idea from what that is or what the purpose is. But it looks funny.
The code is incomplete as everyone has stated above, however it looks suspiciously like the Pear Config for PHP_ParserGenerator.
static function Configlist_add($rp, $dot)
{
$model = new PHP_ParserGenerator_Config;
$model->rp = $rp;
$model->dot = $dot;
$cfp = self::Configtable_find($model);
if ($cfp === 0) {
$cfp = self::newconfig();
$cfp->rp = $rp;
$cfp->dot = $dot;
$cfp->fws = array();
$cfp->stp = 0;
$cfp->fplp = $cfp->bplp = 0;
$cfp->next = 0;
$cfp->bp = 0;
self::$currentend = $cfp;
self::$currentend = &$cfp->next;
self::Configtable_insert($cfp);
}
return $cfp;
}
I would suspect if you look further into the code you will find a reference to this of something similar.