Page 1 of 1

Working with arrays - Perl to PHP

Posted: Thu Oct 23, 2003 7:24 am
by ispwebhosting4u
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

Posted: Thu Oct 23, 2003 8:19 am
by volka
do you know what the purpose of that code snippet is?
As far as I can see...
while ($row = $sth->fetchrow_hashref){
push @{ $users{$row->{'Sponsor'}}}, $row->{'Username'};
}
there's a hash %users holding arrays of usernames indexed by their(?) sponsor
foreach $key (keys %users) {
@new = ();
while (@{$users{$key}}) {
push(@new, splice(@{$users{$key}}, rand @{$users{$key}}, 1));
}
@{$users{$key}} = @new;
}
this (in a strange way) shuffles all elements in each array

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);
?>
should do the same