Dear fellow programmers,
I have a piece of code written in perl that I would like to convert to its PHP equivalent. Below is my attempt at this, but as you can tell, it has been a while since I have worked with perl. Any assistance would be great.
Perl Code:
srand(time|$$);
$sql="SELECT * FROM users";
&Do_SQL;
while ($row = $sth->fetchrow_hashref){
push @{ $users{$row->{'Sponsor'}}}, $row->{'Username'};
}
foreach $key (keys %users) {
@new = ();
while (@{$users{$key}}) {
push(@new, splice(@{$users{$key}}, rand @{$users{$key}}, 1));
}
@{$users{$key}} = @new;
}
My PHP attempt:
//srand(time|$$); I figure I can do without this
$sql="SELECT * FROM users";
$sql_result = mysql_query($sql, $connection) or die ("Couldn't execute query");
while ($row = mysql_fetch_assoc($sql_result)){
array_push( $users, $row["Sponsor"], $row["Username"]);
}
foreach (array_keys($users) as $key) {
$new = array();
// *******Not sure about what's going on with this while loop
while (@{$users{$key}}) {
push(@new, splice(@{$users{$key}}, rand @{$users{$key}}, 1));
} // I know this line of code will use the array_push
@{$users{$key}} = @new; // placing array into assoc. array, maybe?
}
Thanks,
Rick Page
http://www.ISPwebhosting4u.com
Working with arrays - Perl to PHP
Moderator: General Moderators
-
ispwebhosting4u
- Forum Newbie
- Posts: 1
- Joined: Thu Oct 23, 2003 7:24 am
do you know what the purpose of that code snippet is?
As far as I can see...
If(!) I'm correctshould do the same
As far as I can see...
there's a hash %users holding arrays of usernames indexed by their(?) sponsorwhile ($row = $sth->fetchrow_hashref){
push @{ $users{$row->{'Sponsor'}}}, $row->{'Username'};
}
this (in a strange way) shuffles all elements in each arrayforeach $key (keys %users) {
@new = ();
while (@{$users{$key}}) {
push(@new, splice(@{$users{$key}}, rand @{$users{$key}}, 1));
}
@{$users{$key}} = @new;
}
If(!) I'm correct
Code: Select all
<?php
$users = array();
...
while($row = mysql_fetch_assoc($sql_result))
{
if (!isset( $users[$row['Sponsor']] ))
$users[$row['Sponsor']] = array(); // avoid warnings
array_push($users[$row['Sponsor']], $row['Username']);
}
...
srand((float)microtime()*1000000);
foreach($users as $index=>$arr)
$users[$index] = shuffle($arr);
?>