views:

194

answers:

5

Hi Guys,

I want something (final) like this :

<?php
//named as config.php
$fn[0]["long"] = "file name";   $fn[0]["short"] = "file-name.txt";  
$fn[1]["long"] = "file name 1"; $fn[1]["short"] = "file-name_1.txt";
?>

What that I want to?:

1. $fn[0], $fn[1], etc.., as auto increasing
2. "file-name.txt", "file-name_1.txt", etc.., as file name from a directory, i want it auto insert.
3. "file name", "file name 1", etc.., is auto split from "file-name.txt", "file-name_1.txt", etc..,

and config.php above needed in another file e.g.

<? //named as form.php
include "config.php";
for($tint = 0;isset($text_index[$tint]);$tint++)
{
if($allok === TRUE && $tint === $index) echo("<option VALUE=\"" . $text_index[$tint]["short"] . "\" SELECTED>" . $text_index[$tint]["long"] . "</option>\n");
else echo("<option VALUE=\"" . $text_index[$tint]["short"] . "\">" . $text_index[$tint]["long"] . "</option>\n");
} ?>

so i try to search and put php code and hope it can handling at all : e.g.

<?php
$path = ".";
$dh = opendir($path);
//$i=0; 
$i= 1;
while (($file = readdir($dh)) !== false) {
if($file != "." && $file != "..") {
echo "\$fn[$i]['short'] = '$file'; $fn[$i]['long'] = '$file(splited)';<br />"; // Test 
       $i++;
}
}
closedir($dh);
?>

but i'm wrong, the output is not similar to what i want, e.g.

$fn[0]['short'] = 'file-name.txt'; ['long'] = 'file-name.txt'; //<--not splitted
$fn[1]['short'] = 'file-name_1.txt'; ['long'] = 'file-name_1.txt'; //<--not splitted

because i am little known with php so i don't know how to improve code more, there are any good tips of you guys could help me, Please

+1  A: 

Use this as the if condition to avoid the '..' from appearing in the result.

if($file != "." && $file != "..")
codaddict
Ok Codadict, you give a good thing (Thank You), line ['short'] = '..' deleted, but i want more completely, from ['short'] = 'filename.txt' to $fn[0]["short"] = "filename.txt";
jones
+1  A: 

Change

if($file != "." ) {

to

if($file != "." and $file !== "..") {

and you get the behaviour you want.

If you read all the files from a linux environment you always get . and .. as files, which represent the current directory (.) and the parent directory (..). In your code you only ignore '.', while you also want to ignore '..'.

Edit: If you want to print out what you wrote change the code in the inner loop to this:

if($file != "." ) {
  echo "\$fn[\$i]['long'] = '$file'<br />"; // Test
    $i++;
}

If you want to fill an array called $fn:

if($file != "." ) {
  $fn[]['long'] = $file;
}

(You can remove the $i, because php auto increments arrays). Make sure you initialize $fn before the while loop: $fn = array();

Jimmy Shelter
OK that tips deleted ['short'] = '..', than i need ['short'] = 'filename.txt' more complete to $fn[0]["short"] = "filename.txt";, any idea?, Many Thank you
jones
Do you want to print that out, or do you want to fill an array called $fn with that info?
Jimmy Shelter
Yeah... your last code close to done. in fact i use e.g config.php (as file configuration to another file) inside config.php e.g. <? $fn[0]["long"] = "file name"; $fn[0]["short"] = "file_name.txt"; etc..?> and than i think it possible with auto fill input. which $fn[0]["short"] = "file_name.txt"; close to done. and now i much think how to auto split to "file name" and put it to $fn[0]["long"] = "file name";. but in all my heart i appreciate your very helpful, many thank you.
jones
A: 

I've had the same thing happen. I've just used array_shift() to trim off the top of the array check out the documentation. http://ca.php.net/manual/en/function.array-shift.php

Robert Hurst
thank for your info
jones
+1  A: 

Have a look at the following functions:

  • glob — Find pathnames matching a pattern
  • scandir — List files and directories inside the specified path
  • DirectoryIterator — provides a simple interface for viewing the contents of filesystem directories

So, with the DirectoryIterator you simply would do:

$dir = new DirectoryIterator('.');
foreach($dir as $item) {
    if($item->isFile()) {
        echo $file;
    }
} 

Notice how every $item in $dir is an SplFileInfo instance and provides access to a number of useful other functions, e.g. isFile().

Doing a recursive directory traversal is equally easy. Just use a RecursiveDirectoryIterator with a RecursiveIteratorIterator and do:

$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach($dir as $item) {
    echo $file;
}


NOTE I am afraid I do not understand what the following line from your question is supposed to mean:

echo "$fn[$i]['long'] = '$file'<br />"; // Test

But with the functions and example code given above, you should be able to do everything you ever wanted to do with files inside directories.

Gordon
ok bro... many thank you, than i will looking forward ot your link. GBU
jones
Many Thank you for your kindly, please understood that i'm not good both in English or PHPin fact, of lines $fn[0]["long"] = "file name"; $fn[0]["short"] = "filename.txt" etc..; filled inside of config.php as file configuration to another file, that i want is $fn[0]["short"] = "filename.txt" will auto fill with file name from directory and than split it into (become) $fn[0]["long"] = "file name";
jones
Can you please edit your question and paste some parts of `config.php`. From what I understand right now, it is not possible to split the names unless `config.php` contains a mapping of short names to long names or if the filenames follow a naming pattern.
Gordon
Ok, my first Question edited, hope it can help us to understand, and this case also posted at http://www.codingforums.com/showthread.php?p=908591, thank you
jones
+1  A: 

New answer after OP edited his question

From your edited question, I understand you want to dynamically populate a SelectBox element on an HTML webpage with the files found in a certain directory for option value. The values are supposed to be split by dash, underscore and number to provide the option name, e.g.

Directory with Files    >    SelectBox Options
filename1.txt           >    value: filename1.txt, text: Filename 1
file_name2.txt          >    value: filename1.txt, text: File Name 2
file-name3.txt          >    value: filename1.txt, text: File Name 3

Based from the code I gave in my other answer, you could achieve this with the DirectoryIterator like this:

$config = array();
$dir    = new DirectoryIterator('.');
foreach($dir as $item) {
    if($item->isFile()) {
        $fileName = $item->getFilename();
        // turn dashes and underscores to spaces
        $longFileName = str_replace(array('-', '_'), ' ', $fileName);
        // prefix numbers with space
        $longFileName = preg_replace('/(\d+)/', ' $1', $fileName);
        // add to array
        $config[] = array('short' => $filename,
                          'long'  => $longFilename);
    }
} 

However, since filenames in a directory are unique, you could also use this as an array:

$config[$filename] => $longFilename;

when building the config array. The short filename will form the key of the array then and then you can build your selectbox like this:

foreach($config as $short => $long)
{
    printf( '<option value="%s">%s</option>' , $short, $long);
}

Alternatively, use the Iterator to just create an array of filenames and do the conversion to long file names when creating the Selectbox options, e.g. in the foreach loop above. In fact, you could build the entire SelectBox right from the iterator instead of building the array first, e.g.

$dir = new DirectoryIterator('.');
foreach($dir as $item) {
    if($item->isFile()) {
        $fileName = $item->getFilename();
        $longFileName = str_replace(array('-', '_'), ' ', $fileName);
        $longFileName = preg_replace('/(\d+)/', ' $1', $fileName);
        printf( '<option value="%s">%s</option>' , $fileName, $longFileName);
    }
} 

Hope that's what your're looking for. I strongly suggest having a look at the chapter titled Language Reference in the PHP Manual if you got no or very little experience with PHP so far. There is also a free online book at http://www.tuxradar.com/practicalphp

Gordon
jones
I appreciate the offer, but have to decline. Just keep your questions coming here on SO. And don't worry about any payment. If we would want to have money for our answers, we would not answer. So, advice is free here :)
Gordon
Thank for everything Gordon, i just want to get along with you, 'cause you very friendly
jones
but the submit button doesn't work anymore.. if you think you need to learn a whole of my code... and have consider to make more clear this topic here the more complete my piece code at: pastebin.com/m4bbb5ada please do not hesitate to give me more advice and also question as you want. Many Thank You...
jones
I've looked at the pastebin briefly but found it too hard to make sense of it quickly. I think I could figure out what the code does if I had more time at hand, but I suggest to break down the code into smaller discrete functions with meaningful function names to improve readability. Even better would be to use OOP.
Gordon
Cool... I will waiting... but what the meaning of OOP?Thanks for your help so-farMuch Appreciated
jones
Umm, there is no need to wait. What I meant was, I don't have the time to look at it. I am sorry. OOP means Object Oriented Programming. See http://de3.php.net/manual/en/language.oop5.php and http://www.tuxradar.com/practicalphp/6/0/0
Gordon