0

我想要 php 中的 sql left join 功能。

$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 应该等于下面的数组。

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")
)

left_join 函数应该是什么?

4

1 回答 1

1
$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 as $joinKey => $joinValue) {
                if ($joinValue["common_key"] == $entry["common_key"]) {
                    $entry = array_merge($entry, $joinValue);
                    break;
                }
            }
        },
        $table2
    );
    return $table1;
}
于 2013-05-04T11:48:23.310 回答