Hash join: Difference between revisions

added php
m (→‎{{header|REXX}}: added "dummy" code to show how to avoid showing Popeye's entry (it has no nemesis). -- ~~~~)
(added php)
Line 427:
[[2, "Alan"], ["Alan", "Zombies"]]
[[3, "Glory"], ["Glory", "Buffy"]]</pre>
 
=={{header|PHP}}==
<lang php><?php
function hashJoin($table1, $index1, $table2, $index2) {
// hash phase
foreach ($table1 as $s)
$h[$s[$index1]][] = $s;
// join phase
foreach ($table2 as $r)
foreach ($h[$r[$index2]] as $s)
$result[] = array($s, $r);
return $result;
}
 
$table1 = array(array(27, "Jonah"),
array(18, "Alan"),
array(28, "Glory"),
array(18, "Popeye"),
array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
array("Jonah", "Spiders"),
array("Alan", "Ghosts"),
array("Alan", "Zombies"),
array("Glory", "Buffy"),
array("Bob", "foo"));
 
foreach (hashJoin($table1, 1, $table2, 0) as $row)
print_r($row);
?></lang>
{{out}}
<pre>
Array
(
[0] => Array
(
[0] => 27
[1] => Jonah
)
 
[1] => Array
(
[0] => Jonah
[1] => Whales
)
 
)
Array
(
[0] => Array
(
[0] => 27
[1] => Jonah
)
 
[1] => Array
(
[0] => Jonah
[1] => Spiders
)
 
)
Array
(
[0] => Array
(
[0] => 18
[1] => Alan
)
 
[1] => Array
(
[0] => Alan
[1] => Ghosts
)
 
)
Array
(
[0] => Array
(
[0] => 28
[1] => Alan
)
 
[1] => Array
(
[0] => Alan
[1] => Ghosts
)
 
)
Array
(
[0] => Array
(
[0] => 18
[1] => Alan
)
 
[1] => Array
(
[0] => Alan
[1] => Zombies
)
 
)
Array
(
[0] => Array
(
[0] => 28
[1] => Alan
)
 
[1] => Array
(
[0] => Alan
[1] => Zombies
)
 
)
Array
(
[0] => Array
(
[0] => 28
[1] => Glory
)
 
[1] => Array
(
[0] => Glory
[1] => Buffy
)
 
)</pre>
 
=={{header|Python}}==
Anonymous user