类似于sql的东西在php中加入了

时间:2013-05-04 11:09:43

标签: php arrays left-join

我想在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函数应该是什么?

1 个答案:

答案 0 :(得分: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;
}