I working with my simple project which gets the variable name from another php file. Some variables has same value..
I used foreach to display variables in different php files in specific directory..
(1st app_config.php) $app_name = "Pass Generator";
(2nd app_config.php) $app_name = "Random Name Generator";
(3rd app_config.php) $app_name = "Love Meter";
(4th app_config.php) $app_name = "Random Name Generator";
(5th app_config.php) $app_name = "Lucky Number Generator";
Since my 2nd and 4th variable of $app_name has same value, how can I skip one of them. So the output will be:
Pass Generator
Random Name Generator
Love Meter
Lucky Number Generator
This is my code:
$path = '../../apps/' . $name[0];
$results = scandir($path);
foreach ($results as $result) {
if ($result === '.' or $result === '..') continue;
if (is_dir($path . '/' . $result)) {
require_once("../../apps/".$result."/app_config.php");
$app .= $app_name."<Br>";
}
}
echo $app_name;
Anyone? Thanks
$path = '../../apps/' . $name[0];
$results = scandir($path);
$arrProcessed = array();
foreach ($results as $result) {
if ($result === '.' or $result === '..' or array_key_exists($result, $arrProcessed)) continue;
$arrProcessed[$result] = true;
if (is_dir($path . '/' . $result)) {
require_once("../../apps/".$result."/app_config.php");
$app .= $app_name."<Br>";
}
}
echo $app_name;
As an alternative, you could gather them inside an array then implode/glue them with linebreak:
$path = '../../apps/' . $name[0];
$results = scandir($path);
$apps = array();
foreach ($results as $result) {
if ($result === '.' or $result === '..') continue;
if (is_dir($path . '/' . $result)) {
require_once("../../apps/".$result."/app_config.php");
$apps[$app_name] = null;
}
}
echo implode('<br/>', array_keys($apps));
Or another variation:
if (is_dir($path . '/' . $result)) {
require_once("../../apps/".$result."/app_config.php");
$apps[] = $app_name;
}
}
echo implode('<br/>', array_unique($apps));
Related
I have a directory with subdirectories in it, I am trying to loop over all of them and also loop on the filenames to count how many time there is a string inside it.
inside of a subdirectory: (i get this output)
../convo/96376/96376-200-2019-03-28-16-15-49.wav
../convo/96376/96376-200-2019-04-01-11-46-52.wav
../convo/96376/96376-200-2019-04-01-11-47-27.wav
../convo/96376/96376-263-2020-01-06-09-40-24.wav
../convo/96376/96376-263-2020-01-06-10-08-16.wav
Here I need to count how many files have (200) or (263) to make a report.
I already isolated the number i need and stored it in a variable ($poste). I just don't know how I am supposed to make a count here since i have nothing to compare. Here is what i got so far
200 and 263 are not hardcoded (I will never know the numbers in advance) and there could be alot more to count
$directory = '../convo/';
$count = 0;
$subDirectories = scandir($directory);
unset($subDirectories[0]);
unset($subDirectories[1]);
foreach ($subDirectories as $subDirectory) {
echo '<h2>' . $subDirectory . '</h2>';
foreach (glob($directory . $subDirectory . '/*') as $file) {
$poste_explode = explode('-', $file);
$poste = $poste_explode[1];
}
}
if you just need the count for 200 & 263, try this:
$directory = '../convo/';
$count = 0;
$subDirectories = scandir($directory);
unset($subDirectories[0]);
unset($subDirectories[1]);
foreach ($subDirectories as $subDirectory) {
echo '<h2>' . $subDirectory . '</h2>';
foreach (glob($directory . $subDirectory . '/*') as $file) {
$poste_explode = explode('-', $file);
$poste = $poste_explode[1];
if (in_array($poste,["200","263"])) {
$count++;
}
}
}
Just add a test for the values and put a counter here:
$posteCounter = 0;
foreach (glob($directory . $subDirectory . '/*') as $file) {
$poste_explode = explode('-', $file);
$poste = $poste_explode[1];
if(200 == $poste || 263 == $poste) {
$posteCounter++;
}
Or you could count each one so that you have separate values which can be totaled:
//set variables outside the loop to hold the values
$_200 = 0;
$_263 = 0;
if(200 == $poste) {
$_200++;
} elseif (263 == $poste) {
$_263++;
}
EDIT Based on comments provided by the OP:
In order to find all of the poste values and then count you will have to loop twice through your directory. The first loop will build an array:
foreach(glob($directory . $subDirectory . '/*') as $file) {
$poste_explode = explode('-', $file);
$postes[] = $poste_explode[1]; // create and populate $postes array
}
Now you can loop through the $postes array and count files with those values, setting up a variable variable (there are likely better ways, but a lack of coffee isn't bringing them to mind) for each of the poste numbers. Here is an EXAMPLE of an experiment in progress
$filenames = ['a-2-foo', 'b-2-bar', 'c-3-glorp'];
foreach($filenames as $filename){
$poste_explode = explode('-', $filename);
$postes[] = $poste_explode[1];
if(!isset(${'poste_' . $poste_explode[1]})){
${'poste_' . $poste_explode[1]} = 0; // set up variable variable
}
}
var_dump( get_defined_vars() );
print_r($postes);
foreach($postes as $poste){
echo $poste . "\n";
foreach($filenames as $filename){
$poste_explode = explode('-', $filename);
if($poste == $poste_explode[1]){
echo ${'poste_' . $poste} . "\n";
${'poste_' . $poste}++; // variable variable
}
}
}
In mydirectory
green.txt
black.txt
shadow.txt
and my php code
<?php
$key = "black+shadow"
$dir = 'file/dir';
$ext = '.txt';
$i=0;
$search = $key;
$results = glob("$dir/*$search*$ext");
if(count($results) != 1) {
foreach($results as $item) {
echo $item;
}
}?>
I want to get the output "black.txt" and "shadow.txt"
$key = "black+shadow";
$dir = "file/dir"
$ext = '.txt';
foreach (explode("+", $key) as $filePart) {
$fileName = $filePart . $ext;
if (file_exists("{$dir}/{$fileName}")) {
echo $fileName . '<br>';
}
}
This assumes that the pattern will always be filepart separated by +
You can use glob if you end up with more complex solutions - but this is probably the fastest and easiest way to understand IMHO.
<?php
$key = "{black,shadow}";
$ext = '.txt';
$i=0;
$search = $key;
$results = glob("$search*$ext",GLOB_BRACE);
if(count($results) != 1) {
foreach($results as $item) {
echo $item;
}
}?>
per the manual,
GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
i added braces around your search terms and added the GLOB_BRACE flag.
(dir removed as i ran a local test)
I have a php search code that returns the results in the page. What I wanna do is limit the number of results per page to 10, and echo a link for more results.
My code is:
$dir = 'www/posts';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
if (!empty($q)) {
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
$fpath = 'posts/'.$file;
if (file_exists($fpath)) {
echo "<a href='/search.php?post=$withoutExt'>$withoutExt</a>" . " on " . date ("d F Y ", filemtime($fpath)) ;
echo "<br>";
}
}
}
closedir($res);
}
else {
echo "";
}
I tried the $q->limit(10); but it doesnt work. Please help me write a working code.
<?php
$dir = 'www/posts';
$exclude = array(
'.',
'..',
'.htaccess'
);
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$results=[];
if (! empty($q)) {
$res = opendir($dir);
while (false !== ($file = readdir($res))) {
if (strpos(strtolower($file), $q) !== false && ! in_array($file, $exclude)) {
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
$fpath = 'posts/' . $file;
if (file_exists($fpath)) {
$results[]="<a href='/search.php?post=$withoutExt'>$withoutExt</a>" . " on " . date("d F Y ", filemtime($fpath));
}
}
}
closedir($res);
}
foreach ($results as $result) {
echo $result;
echo "<br>";
}
if (count($results) > 10 ) {
echo 'results is more than 10, but only 10 results is shown';
}
Here is a completely untested suggestion... I am happy to have a bit of back and forth to iron it out.
if(!empty($_GET['q'])){
// perform some logical validation/sanitization on `$_GET['q']` for stability/security
$path = '../posts'; // this relative path may need some adjusting
$files=glob("$path/*.txt"); // collect all .txt files from the directory
var_export($files);
$filtered=preg_grep('~.*'.preg_quote($q,'/').'.*\.txt$~i',$files); // case-insensitive filename search
var_export($filtered);
if(!empty($filtered)){
$batches=array_chunk($filtered,10); // store in groups of 10
var_export($batches); // check the data
if(!isset($_GET['page'],$batches[--$page])){ // a page has been submitted and that page exists in the batches array (subtract one to sync the page with the index)
$page=0;
}
$leftovers=array_keys(array_diff_key($batches,[$page=>'']));
foreach($batches[$page] as $filename){
$withoutExt=substr($filename,0,strrpos($filename,"."));
$fpath="posts/$filename";
echo "<div><a href='/search.php?post=$withoutExt'>$withoutExt</a> on ",date("d F Y",filemtime($fpath)),"</div>";
}
// here you can list the other pages available from this search
if($leftovers){
echo "Additional pages:";
foreach($leftovers as $offset){
echo " <a href='/search.php?q={$_GET['q']}&page=",++$offset,"'>$offset</a>";
}
}
}
}else {
echo "No Search Terms found";
}
This code below will echo the keyword in each file, Is it possible to get the results (Keyword from each file) to display in alphabetical order.
<?php
$files = (glob('{beauty,careers,education,entertainment,pets}/*.php', GLOB_BRACE));
$selection = $files;
$files = array();
$keywords = $matches[1];
foreach ($selection as $file) {
if (basename($file) == 'index.php') continue;
if (basename($file) == 'error_log') continue;
$files[] = $file;
}
foreach($files as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$content = file_get_contents($file);
if (!$content) {
echo "error reading file $file<br>";
}
else {
preg_match("/keywords = \"(.*?)\"/i", $content, $matches);
$keywords = $matches[1];
}
$results .= '<li>'.$keywords.'</li>';
}
?>
<?=$results?>
Use sort() to sort the keyword array:
$keywords = array();
// ...
$keywords[] = $matches[1];
sort($keywords);
use sort() on $keywords. There's some spelling mistakes and unused varaibles. You need to not build your $results HTML until all the files are processes, so move that $results = '' out of the foreach loop that processes the files, then sort, then foreach the keywords and build up $results.
<?php
$selection = (glob('{beauty,careers,education,entertainment,pets}/*.php', GLOB_BRACE));
$files = array();
// $keywords = $matches[1];
foreach ($selection as $file) {
if (basename($file) == 'index.php') continue;
if (basename($file) == 'error_log') continue;
$files[] = $file;
}
foreach($files as $file) {
//$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$content = file_get_contents($file);
if (!$content) {
echo "error reading file $file<br>";
}
else {
preg_match("/keywords = \"(.*?)\"/i", $content, $matches);
$keywords[] = $matches[1];
}
}
$results = '';
sort($keywords); //comment this out to see the effects of the sort()
foreach($keywords as $_k) {
$results .= '<li>'.$_k.'</li>';
}
?>
<?=$results?>
I'm writing code that I'd like to recursively list directories. So far I've written code that lists level 1 directories. Does anyone have any ideas about how I can recurse infinitely?
$res = OC_Files::getDirectoryContent('');
$list = array();
foreach($res as $file) {
if ($file['type'] == 'dir') {
$res1 = OC_Files::getDirectoryContent('/'.$file['name']);
foreach($res1 as $res2) {
if ($res2['type'] == 'file') $list[] = $file['name'].'/'.$res2['name'];
}
} else $list[] = $file['name'];
}
foreach($list as $entry)
echo $entry.'</br>';
Try this:
function traverse_directory($dir) {
$res = OC_Files::getDirectoryContent($dir);
$list = array();
foreach($res as $file) {
if ($file['type'] == 'dir') {
traverse_directory($dir . '/' . $file['name'])
} else {
$list[] = $file['name'];
}
}
foreach($list as $entry) {
echo $entry.'</br>';
}
}
traverse_directory('');