Domanda

I'm trying to make a php function that names the very first uploaded image: a.png, the next one, b.png, and after it finishes the alphabet and numbers, it will continue as: aa.png, ab.png, ect (extending the string size once it finishes). I'd like to have an array of characters to go through in order, not just the alphabet:

$charset = 'abcdefghijklmnopqrstuvwxyz';
$charset .= '0123456789';
$charset .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

And it would store the last image name (ect ab3.png) so it could continue at ab4.png next time it runs.

Does anyone know or have such a function like this? Or could you guys help me out?

È stato utile?

Soluzione

Do you have a particular reason for wanting to do it this way? Or are you trying to come up with a way to create unique file names? If its the latter, then have a look at PHP's uniqid function.

In that case, how about this, it doesn't fulfill all your requirements, but will get you much closer:

function createId($numId) {
    $result = '';
    $mod = 26;
    $quotient = $numId;

    while ($quotient >= 0) {
        $result .= chr(65 + ($quotient % $mod));
        $quotient = $quotient / $mod - 1;
    }

    return $result;
}

And with the following calls:

print createId(0) . "\n";
print createId(25) . "\n";
print createId(26) . "\n";
print createId(8) . "\n";
print createId(9876) . "\n";

gives you:

A

Z

AA

I

WON

Altri suggerimenti

Just made something sloppy as you asked.

$id = 128;

$charset = 'abcdefghijklmnopqrstuvwxyz';
$charset .= '0123456789';
$charset .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

$len = strlen($charset);
$ret = '';
$tmp = $id;
$it = ceil($tmp / $len);
for($i = 0; $i < $it; $i++) {
    $ret .= $charset[($tmp > $len) ? 0 : $tmp % $len];
    $tmp -= $len;
}


echo $ret;

the $id should be the incremental primary ID in your database.

EDIT: Not entirely how you wanted it. Nevermind, take Dan's solution.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top