arrays - something similar to sql left join in php -
i want sql left join functionality in php.
$table1 = array( 0 => array("id" => "id1", "common_key" => 1), 1 => array("id" => "id2", "common_key" => 2), 2 => array("id" => "id3", "common_key" => 1) ); $table2 = array( 0 => array("name" => "name1", "common_key" => 1), 1 => array("name" => "name2", "common_key" => 2) ); $result = left_join($table1, $table2);
$result should equal array below.
array( 0 => array("id" => "id1", "common_key" => 1, "name" => "name1"), 1 => array("id" => "id2", "common_key" => 2, "name" => "name2"), 2 => array("id" => "id3", "common_key" => 1, "name" => "name1") )
what should left_join function?
$table1 = array( 0 => array("id" => "id1", "common_key" => 1), 1 => array("id" => "id2", "common_key" => 2), 2 => array("id" => "id3", "common_key" => 1) ); $table2 = array( 0 => array("name" => "name1", "common_key" => 1), 1 => array("name" => "name2", "common_key" => 2) ); $result = left_join($table1, $table2); var_dump($result); function left_join($table1, $table2) { array_walk( $table1, function(&$entry, $key, $jointable) { foreach($jointable $joinkey => $joinvalue) { if ($joinvalue["common_key"] == $entry["common_key"]) { $entry = array_merge($entry, $joinvalue); break; } } }, $table2 ); return $table1; }
Comments
Post a Comment