I have a image named Dark-Green.jpg but the output of function is DARK-GREEN.jpg so the image is not displaying due to case-sensitive.
So how can I fetch the image?
UPDATE
Below is my output of the array.
$output = Array
(
[WE05-5040*L] => Array
(
[qty] => 1
[stitching_category] => 2
[sku_image] => skuimages/WE05/DARK-GREEN.jpg
)
)
Then I am using this array in foreach loop like below.
foreach ($output as $ok => $op) {
$itemQty = $op['qty'];
$itemImagePath = $op['sku_image'];
echo "{$ok} has qty: {$itemQty} and the image as below.";
echo "<img src='{$itemImagePath}' width='50%' />"
}
Try this:
function getFile ($filename){
$files = glob($dir . '/*');
$filename = strtolower($filename);
foreach($files as $file) {
if (strtolower($file) == $filename){
return $file;
}
}
return false;
}
I have a folders/files tree inside admin folder (windows, localhost).
All files are .html.
Each of them (files and folders) is starting with some numbers and middle dash, for example
32-somefolder
624-somefile.html
I need to list all of them and remove all prefixes from their names.
So the result should be:
somefolder
somefile.html
foreach(glob("admin/*") as $el) {
echo $el . '.' . filetype($el) . '<br>';
}
First problem - only folders are listed:
admin/32-somefolder.dir
How to get files too, and how to rename i.e. remove prefixes from all the names?
You can use the second choice to list files : scandir, and recursive function :
function removePrefixFiles($dir, &$results = array()){
$files = scandir($dir);
foreach ($files as $key => $value){
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (! is_dir($path)) {
// treat the filename
$file = pathinfo($path);
$filename = explode('-', $file['filename']);
if (count($filename) > 0) {
// '-' is found, rename file
rename($path, $file['dirname'] .'/'. $filename[1] .'.'. $file['extension'];
}
$results[] = $path;
} else if ($value != '.' && $value != '..') {
removePrefixFiles($path, $results);
$results[] = $path;
}
}
// no real need to return something here, but can log the files
return $results;
}
$dir = '/admin';
removePrefixFiles($dir);
I have created two folder inside admin/ name as
1-files and 2-abc
then inside folder 1-files i have two files
11-java.html
11-text.html
then inside folder 2-abc i have two files
22-php.html
22-sql.html
<?php
$dir = "admin/";
// Sort in ascending order - this is default
$a = scandir($dir);
echo "<pre>";
if(count($a)>0){
$newArr = array();
for($i=2;$i<count($a);$i++){
$test = array();
$folderArr = array();
$folderName = explode('-',$a[$i]);
$test['folder'] = $folderName[1];
$b = scandir($dir.'/'.$a[$i]);
for($j=2;$j<count($b);$j++){
$fileName = explode('-',$b[$j]);
$folderArr[] = substr($fileName[1], 0, strpos($fileName[1], "."));;
}
$test['files'] = $folderArr;
$newArr[] = $test;
}
}
print_r($newArr);
?>
This will be the output
Array
(
[0] => Array
(
[folder] => files
[files] => Array
(
[0] => java
[1] => text
)
)
[1] => Array
(
[folder] => abc
[files] => Array
(
[0] => php
[1] => sql
)
)
)
Hope this willl hellp you.
I have a list of IDs
$Ids="1201,1240,1511,1631,1663,1666,1716,2067,2095";
and in the /imgs/ folder there are many jpg filenames related to these IDs. But there are a lot of IDs that do not have any image.
for example there are in the /imgs/
1201_73.jpg
1201_2897.jpg
1240-9834.jpg
1240-24.jpg
1511-dsc984.jpg
1511-dsc34.jpg
What I want to achieve is to find which of the IDs have images in the img folder.
Thank you
Updated
$array = array();
$foo = explode('.jpg', $images);
foreach($foo as $id) {
$digi = substr(trim($id), 0,4);
if(!in_array($digi, $array)) {
array_push($array, $digi);
echo $id . ".jpg <br/>";
$where .= "id='$digi' or ";
}
}
First, turn your string of IDs into an array.
$idsArray = explode(',', $Ids);
Now iterate through the directory, checking each file to see if it starts with the ID.
$hasImages = array();
foreach (new DirectoryIterator(__DIR__ . '/imgs') as $fileInfo) {
if ($fileInfo->isDot() || $fileInfo->isDir()) {
continue;
}
foreach ($idsArray as $id) {
if (0 === strpos($fileInfo->getBasename(), $id)) {
$hasImages[] = $id;
break;
}
}
}
$hasImages = array_unique($hasImages);
$hasImages will contain an array of IDs which have an image.
Something like this should work:
$files = glob('/imgPath/*.jpg');
$hasImage = array_unique(array_map(function($file) {
return explode('-', $file)[0];
}, $files));
$withimages= array_diff(explode($Ids), $hasImage);
I'm trying to write a function that returns and array of the files names ordered by time modified.
Although I want to get only a specific number of files, and not the whole files in the directory.
In conclusion, I'd like to get an array that contains the newest X files from a directory.
This is my code:
public static function GetPicsDir()
{
$results = array();
$handler = opendir("pics");
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$results[] = $file;
}
}
closedir($handler);
return $results;
}
I don't know how to limit it and order by time modified.
I'd be glad to get any help.
Thank you
Use filemtime():
public static function GetPicsDir()
{
$results = array();
$handler = opendir("pics");
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$results[$time] = filemtime($file);
}
}
arsort($results);
closedir($handler);
return $results;
}
You can use glob
$date = strtotime('2013-01-10 10:00:00');//The date from you want to get the files
$matches = glob('dir/*.*');
$result=array();
if (is_array($matches)) {
$a=0;
foreach ($matches as $filename) {
if (filemtime($filename) >= $date) {//only output file >= your $date
$result[$a]['FileName'] = $filename;
$result[$a]['DateCreated'] = gmdate("Y-m-d H:i:s", filemtime($filename));
}
$a++;
}
}
if(count($result)>=2){//order array if it has at least 1 match
foreach ($result as $key => $row) {
$new_array[$key] = $row['DateCreated'];
}
array_multisort($new_array,SORT_DESC,$result);//Show most recent first
}
using array_multisort to sort by dates SORT_DESC
echo '<pre>';
print_r($result);
echo '<pre>';
Output:
Array
(
[0] => Array
(
[FileName] => test.php
[DateCreated] => 2013-10-20 05:43:06
)
[1] => Array
(
[FileName] => test.sql
[DateCreated] => 2013-09-20 23:38:05
)
[2] => Array
(
[FileName] => general.php
[DateCreated] => 2013-09-02 00:58:33
)
)
If you only want to sort the files by last modified date, you can use
ftp_nlist($conn, '-t .');
This will not tell you what the date for each file is, though.
If you want to get the modified date as well, you can use ftp_rawlist and parse the output. Here's a quick example I scraped together:
$list = ftp_rawlist($ftp, '.');
$results = array();
foreach ($list as $line) {
list($perms, $links, $user, $group, $size, $d1, $d2, $d3, $name) =
preg_split('/\s+/', $line, 9);
$stamp = strtotime(implode(' ', array($d1, $d2, $d3)));
$results[] = array('name' => $name, 'timestamp' => $stamp);
}
usort($results, function($a, $b) { return $a['timestamp'] - $b['timestamp']; });
At this point $results contains a list sorted in ascending last modified time; reverse the sort function to get the list in most recently modified first format.
I have following records in text file, need to extract that record form text file and treat them as seperate array variables
r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8) seperated by pipe(|)
I need to represent that as array use seperately like below
$r1= Array
(
[0] => 1
[1] => 2
[2] => 3
)
$r2=Array
(
[0] => 4
[1] => 5
[2] => 6
)
I have no idea how to do it, is it possible in php?
Just a plain regular expression to break up the string, followed by an explode on each group:
if (preg_match_all('#(\w+)=\(([\d,]*)\)#', $s, $matches)) {
foreach ($matches[2] as $i => $groups) {
$group_name = $matches[1][$i];
$$group_name = array_map('intval', explode(',', $groups));
}
}
print_r($r1);
print_r($r3);
print_r($rn);
You can use Eval
//Assuming you can pull the content from text file using fread
$temp = "r1=(1,2,3)|r2=(4,5,6)";
$temp=str_replace("=","=array",$temp);
$split=explode("|",$temp);
echo "<pre>";
foreach($split as $k=>$v){
$v="$".$v.";";
//Evaluate a string as PHP code .i.e You will get r1,r2 as a variable now which is array
eval($v);
}
print_r($r1);
print_r($r2);
$data = "r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";
$arr = explode("|", $data);
$finArray = array();
foreach($arr as $key=>$value)
{
$single = explode('(', $value);
$finArray[] = explode(',', str_replace(')', '', $single[1]));
}
print_r($finArray);
can be done as:
$string="r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";
$string=str_repla("r1=","",$string);
$yourArray=explode('|', $string);
This code will help you:--
<?php
$file = "/tmp/file1.txt"; // this is your file path
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
print $line;
$a=explode('|',$line);
print_r($a); // I have explode based on | for you...
foreach($a as $key=>$value)
{
print_r($value);
}
fclose($file);
}
?>
""or""
$a="r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";
$a=explode('|',$a);
print_r($a);
<?php
$file = "file.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
$str = $line;
}
$str1 = explode("|",$str);
foreach($str1 as $temp) {
$str2 = explode("=",$temp);
$data[$str2[0]] = explode(",",trim($str2[1],"()"));
}
echo '<pre>';
print_r($data);
echo '</pre>';
?>
This will do your job.