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
}
}
}
Related
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 the for loop:
I have an $request->photos array. Keys from this array are:
[1,3,5,8]
In the end, I need to get an array, where indexes are from 1 to 8 and items are boolean variables. Aside from this, I need to save the photos from the array.
Then I need to loop through the array and check if $i equals to $key:
foreach($request->photos as $key => $photo) {
for($i = 1; $i < 9; $i++) {
if ($key == $i) {
dump($key);
$path = storage_path('app/public/images/' . $pdf->id . '-' . $key . '.png');
$image = Image::make($photo->getRealPath())->widen(300)->save($path);
$imagesArray[$i] = true;
break;
} else {
$imagesArray[$i] = false;
}
}
}
And if $key equals to $i, I need to exit from loop. But in this case, break doesn't work and for loop goes on even if $key was found.
Why it goes like that?
The for loop is unnecessary. Just use the keys of $request->photos as the keys to fill in $imagesArray.
$imagesArray = array_fill(1, 8, false);
foreach ($request->photos as $key => $photo) {
dump($key);
$path = storage_path('app/public/images/' . $pdf->id . '-' . $key . '.png');
$image = Image::make($photo->getRealPath())->widen(300)->save($path);
$imagesArray[$key] = true;
}
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));
I am working on a php site that needs to search a set of files with any combination of search fields.
The possible search fields are
id, year, building, lastname, firstname, birthdate
The folder structure and file names are as such
/year/building/file.pdf
The filenames contain the data to search
id_lastname_firstname_MM_dd_yy.pdf
I have everything working on the site except this part. Originally I only had ID, year, and building and I was able to do if's to check for every possibility of combinations. Now there is way more combinations so it much more complex.
I was thinking nested if and in_array or such, but there has to be a better way. I just learning my way around php.
I would like to be able to search with any combination of fields. I can change the filenames if it helps.
I started with something like this
function search($transcripts, $studentid=null, $year=null, $building=null, $last=null, $first=null, $birthdate=null){
$ext = '.pdf';
date_default_timezone_set('America/Los_Angeles');
$dir_iterator = new RecursiveDirectoryIterator("../transcripts");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
if ($file->isFile()){
$path = explode('\\',$file->getPath());
$fname = explode('_', $file->getBasename($ext));
if($path[1] == $year){
if($path[2] == $building){
if(in_array($last, $fname, true)){
if((in_array($first, $fname, true)){
if((in_array($birthdate
Originally I had seperate functions depending on which fields where filed in.
function bldStuSearch($building, $studentid, $transcripts){
$ext = '.pdf';
date_default_timezone_set('America/Los_Angeles');
$dir_iterator = new RecursiveDirectoryIterator("../transcripts");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
$results = explode('\\',$file->getPath());
//var_dump($results);
if (($file->isFile()) && ($file->getBasename($ext)==$studentid) && ($results[2] == $building)){
//echo substr($file->getPathname(), 27) . ": " . $file->getSize() . " B; modified " . date("Y-m-d", $file->getMTime()) . "\n";
$results = explode('\\',$file->getPath());
//var_dump($results);
//$building = $results[2];
$year = $results[1];
//$studentid = $file->getBasename($ext);
array_push($transcripts, array($year, $building, $studentid));
//var_dump($transcripts);
//$size += $file->getSize();
//echo '<br>';
}
}
//echo "\nTotal file size: ", $size, " bytes\n";
if (empty($transcripts))
{
header('Location: index.php?error=2'); exit();
}
return $transcripts;
}
Now I am trying to have one search function to check for any combination? Any idea that would at least put in the right direction?
Thanks.
So I had an idea about doing a scoring system but then dismissed it. I came back to it and found a way to make it work using a weighted scoring system.
This allows the search to be super flexible and maintain being portable, not requiring a database for the metadata and using the filename as the search data without having to search each PDF. I am using A-Pdf splitter to split the PDF into separate files and add the metadata to the filename.
I hope someone some day finds this useful for other searches. I am really happy the way this turned out.
I will post the entire code when I am done on http://github.com/friedcircuits
One thing I should change is to use named keys for the arrays.
Here is the resulting code. Right now the birthdate has to be entered as m-d-yyyy to match.
function search($transcripts, $studentid=null, $year=null, $building=null, $last=null, $first=null, $birthdate=null){
$ext = '.pdf';
$bldSearch = false;
date_default_timezone_set('America/Los_Angeles');
if (($building == null) AND ($year == null)){ $searchLocation = "../transcripts";}
elseif (($year != null) AND ($building != null)){$searchLocation = "../transcripts/".$year."/".$building;}
elseif ($year != null) {$searchLocation = "../transcripts/".$year;}
elseif ($building != null) {
$searchLocation = "../transcripts/";
$bldSearch = true;
}
else{$searchLocation = "../transcripts";}
$dir_iterator = new RecursiveDirectoryIterator($searchLocation);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
$score = 0;
foreach ($iterator as $file) {
if ($file->isFile()){
//Fix for slashes changing direction depending on search path
$path = str_replace('/','\\', $file->getPath());
$path = explode('\\',$path);
$fname = explode('_', $file->getBasename($ext));
//var_dump($path);
//echo "<br>";
//var_dump($fname);
//echo "<br>";
//fix for different search paths
if($path[1] == "transcripts"){
$pYear = $path[2];
$pbuilding = $path[3];
}
else{
$pYear = $path[1];
$pbuilding = $path[2];
}
if ($bldSearch == true){
if ($building != $pbuilding) {continue;}
}
//$fname[1] = #strtolower($fname[1]);
//$fname[2] = #strtolower($fname[2]);
if($fname[0] == $studentid){
$yearS = $pYear;
$buildingS = $pbuilding;
$studentidS = $fname[0];
$lastS = $fname[1];
$firstS = $fname[2];
$birthdateS = $fname[3];
array_push($transcripts, array($yearS, $buildingS, $studentidS, $lastS, $firstS, $birthdateS));
continue;
}
if($pYear == $year){
$score += 1;
}
if($path[2] == $building){
$score += 1;
}
if(#strpos(#strtolower($fname[1]),$last) !== false){
$score += 3;
}
if(#strpos(strtolower($fname[2]), $first) !== false){
$score += 3;
}
if($fname[3] == $birthdate){
$score += 3;
}
//echo $score." ";
if ($score > 2) {
$yearS = $pYear;
$buildingS = $pbuilding;
$studentidS = $fname[0];
$lastS = $fname[1];
$firstS = $fname[2];
$birthdateS = $fname[3];
array_push($transcripts, array($yearS, $buildingS, $studentidS, $lastS, $firstS, $birthdateS));
//var_dump($transcripts);
}
}
$score = 0;
}
if (empty($transcripts))
{
header('Location: index.php?error=2'); exit();
}
return $transcripts;}
I am using this PHP code to get and display the number of visitors to my site (hit counter).
Currently it is set up to display that number in a single block, i.e. - I would like to display each digit in its own html tag in order to style each number differently.
I have experimented with explode, and substr on the $allHits var, but am not getting good results.
Any Ideas?
<?
/*----------------------------
-------- ++ simPHP ++ --------
A simple PHP hit counter.
Description:
simPHP counts both regular and unique views on multiple
webpages. The stats can be displayed on any PHP-enabled
webpage. You MUST have read/write permissions on files.
Script by Ajay: ajay#scyberia.org
http://scyberia.org
----------------------------*/
/*----------CONFIG----------*/
// NOTE: If you change any config after using simphp,
// remove the old files.
// Relative URL of text file that holds hit info:
$lf_name = "hits.txt";
// Save new log file each month
// 0 = No
// 1 = Yes
$monthly = 1;
// Path to store old files:
// Default for June, 2012:
// oldfiles/6-12.txt
$monthly_path = "oldfiles";
// Count unique hits or all hits:
// 0 = All hits
// 1 = Unique hits
// 2 = Both
$type = 2;
// Text to display
// before all hits.
$beforeAllText = "Site Visitors: ";
// Before unique hits.
$beforeUniqueText = "Unique Visits: ";
// Display hits on this page:
// 0 = No
// 1 = Yes
$display = 1;
// Only change this if you are recording both values.
// Separator for unique and all hits display - use HTML tags! (line break is default)
$separator = "<br \>";
// Default would output:
// Visits: 10
// Unique Visits: 10
/*--------------------------*/
/*--------BEGIN CODE--------*/
$log_file = dirname(__FILE__) . '/' . $lf_name;
//Check for "?display=true" in URL.
if ($_GET['display'] == "true") {
//Show include() info.
die("<pre><? include(\"" . dirname(__FILE__) . '/' . basename(__FILE__) . "\"); ?></pre>");
} else {
//Visit or IP.
$uIP = $_SERVER['REMOTE_ADDR'];
//Check for "hits.txt" file.
if (file_exists($log_file)) {
//Check if today is first day of month
if (date('j') == 10) {
//Ensure that monthly dir exists
if (!file_exists($monthly_path)) {
mkdir($monthly_path);
}
//Check if prev month log file exists already
$prev_name = $monthly_path . '/' . date("n-Y", strtotime("-1 month"));
if (!file_exists($prev_name)) {
//If not, move/rename current file
copy($log_file, $prev_name);
//Create new $toWrite based on CONFIG
//Write file according to CONFIG above.
if ($type == 0) {
$toWrite = "1";
$info = $beforeAllText . "1";
} else if ($type == 1) {
$toWrite = "1;" . $uIP . ",";
$info = $beforeUniqueText . "1";
} else if ($type == 2) {
$toWrite = "1;1;" . $uIP . ",";
$info = $beforeAllText . "1" . $separator . $beforeUniqueText . "1";
}
goto write_logfile;
}
}
//Get contents of "hits.txt" file.
$log = file_get_contents($log_file);
//Get type from CONFIG above.
if ($type == 0) {
//Create info to write to log file and info to show.
$toWrite = intval($log) + 1;
$info = $beforeAllText . $toWrite;
} else if ($type == 1) {
//Separate log file into hits and IPs.
$hits = reset(explode(";", $log));
$IPs = end(explode(";", $log));
$IPArray = explode(",", $IPs);
//Check for visitor IP in list of IPs.
if (array_search($uIP, $IPArray, true) === false) {
//If doesnt' exist increase hits and include IP.
$hits = intval($hits) + 1;
$toWrite = $hits . ";" . $IPs . $uIP . ",";
} else {
//Otherwise nothing.
$toWrite = $log;
}
//Info to show.
$info = $beforeUniqueText . $hits;
} else if ($type == 2) {
//Position of separators.
$c1Pos = strpos($log, ";");
$c2Pos = strrpos($log, ";");
//Separate log file into regular hits, unique hits, and IPs.
$pieces = explode(";", $log);
$allHits = $pieces[0];
$uniqueHits = $pieces[1];
$IPs = $pieces[2];
$IPArray = explode(",", $IPs);
//Increase regular hits.
$allHits = intval($allHits) + 1;
//Search for visitor IP in list of IPs.
if (array_search($uIP, $IPArray, true) === false) {
//Increase ONLY unique hits and append IP.
$uniqueHits = intval($uniqueHits) + 1;
$toWrite = $allHits . ";" . $uniqueHits . ";" . $IPs . $uIP . ",";
} else {
//Else just include regular hits.
$toWrite = $allHits . ";" . $uniqueHits . ";" . $IPs;
}
//Info to show.
$info = $beforeAllText . $allHits . $separator . $beforeUniqueText . $uniqueHits;
}
} else {
//If "hits.txt" doesn't exist, create it.
$fp = fopen($log_file ,"w");
fclose($fp);
//Write file according to CONFIG above.
if ($type == 0) {
$toWrite = "1";
$info = $beforeAllText . "1";
} else if ($type == 1) {
$toWrite = "1;" . $uIP . ",";
$info = $beforeUniqueText . "1";
} else if ($type == 2) {
$toWrite = "1;1;" . $uIP . ",";
$info = $beforeAllText . "1" . $separator . $beforeUniqueText . "1";
}
}
write_logfile:
//Put $toWrite in log file
file_put_contents($log_file, $toWrite);
//Display info if is set in CONFIG.
if ($display == 1) {
}
}
Would using a foreach loop work, like this:
$array_allHits = explode(" ",$allHits);
foreach ($array_allHits as $display_digits) {
echo $display_digits[0];
}
You could use a for-loop.
for ($i = 0; $i < strlen((string) $allHits); $i++) {
echo '<span>' . $allHits[$i] . '</span>';
}
The above code will output <span>{number}</span> for every digit in the hit count.
It will loop through every character in the string, similar as to how array indexes are treated.
$totalHits = 125655;
foreach(str_split((string)$totalHits) as $key => $val) {
echo "<span class='position_{$key}'>{$val}</span>";
}
Add styles in you css as below:
.position_0 {
color: red;
}
.position_1 {
color: blue;
}
.position_2 {
color: yellow;
}