2013-05-04 56 views
0

我想在PHP中的SQL左連接功能。類似於sql的東西左加入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應該等於下面的數組。

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函數?

+0

這個數組的名字不應該是空的嗎? '2 => array(「id」=>「id3」,「common_key」=> 1,「name」=>「name1」)' – ghost 2013-05-04 11:23:51

+0

no。它應該與mysql jeft join相同 – DamithK 2013-05-04 11:28:23

+0

PHPLinq(https://phplinq.codeplex.com/)是任何類似的庫,如plinq(https://plinq.codeplex.com/)或linqforphp(https:/ /linqforphp.codeplex.com/)給你你需要什麼? – 2013-05-04 11:28:33

回答

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; 
} 
+0

工作正常。謝謝。 – DamithK 2013-05-04 12:56:27

相關問題