tags:

views:

43

answers:

1

Hi there,

I am after a function which will let me sort a bunch of filenames over 4 arrays. However, the a file must always end up in the same array - even if the number of files change.

Eg if I have files myfile.html anotherfile.html morefiles.html test.html

and my arrays array1, array2, array3, array4

If I run this function then array1 might get myfile.html and anotherfile.html

If I run it again and add some more files (or less files, like not pass anotherfile.html) then I would still expect array1 to get myfile.html

So just need some way to hash the filename which I can then use to point to a certain array, so not a random or one that checks how many files are in each array needs to be consistent.

+2  A: 

There are many different ways to solve a task like this, what is below is a very basic introduction to the topic. If it is useful, great otherwise I hope it at least gives an idea what where you might want to go (or not!).

This example simple takes a hash of the filename (in this case MD5 just because you're probably familiar with it). The sscanf just gets the first character of the hash and turns it into a number between 0 and 15 (since md5() returns a hexadecimal number). Since we only want to distribute between four arrays, the modulus operator (%) is used so that $num will always result in 0, 1, 2 or 3 which is then used as an array key (c.f. your $array1, $array2, etc.).

$files = array('a.html','b.html','c.html','d.html');
$arrays = 4;
$array = array_fill(0, $arrays, array());
// For each file name put it into the appropriate slot in $array
foreach ($files as $filename) {
    sscanf(md5($filename), '%1x', $hex);
    $key = $hex % $arrays;
    $array[$key][] = $filename;
}
// See what happened
var_dump($array);

For this particular example, the resulting array (which you can push into your separate variables if you like) has the following structure:

$array = array(
    0 => array()
    1 => array('c.html')
    2 => array('d.html')
    3 => array('a.html', 'b.html')
);
salathe
Thats fantastic! Right what I was after.
Wizzard