2015-10-13 143 views
0

好吧,所以我有這個查詢,它工作得很好,但它不會返回我想要的。PHP Mysqli從JOIN返回數組(別名作爲數組鍵)

SELECT acc.*, fin.* 
FROM consumers acc 
LEFT JOIN finances fin ON fin.uid = acc.uid 
WHERE acc.id = '$userID'; 

這其中鍵是0和所有列(兩個表)是相同的陣列下返回一個數組(在php)。

我想要實現的是獲得2個數組,1個來自第一個表的列,另一個來自第二個表的列。

基本上我試圖從1查詢中得到一個多維數組。

+0

'account' should' acc' – Barmar

+0

沒有辦法自己做你想做的事。當你在while($ row = mysqli_fetch_assoc())'循環中時,將列分配到兩個不同的數組中。 – Barmar

+0

儘管我在這裏重寫了這個查詢,但仍然不起作用。 –

回答

0

讀取行後,將它分成兩個數組。

$row = mysqli_fetch_assoc($query); 
$acc = array($row['col1'], $row['col2'], ...); 
$fin = array($row['col6'], $row['col7'], ...); 

其中col1, COL2 , ... are the columns from消費者, and COL6 , COL7 , ... are the columns from $ finances`。

做到這一點,而不列出的所有列名的方法是用array_slice()

$row = mysqli_fetch_assoc($query); 
$acc = array_slice($row, 0, $number_of_consumer_columns); 
$fin = array_slice($row, $number_of_consumer_columns, $number_of_finances_columns); 
$table3 = array_slice($row, $number_of_consumer_columns + $number_of_finances_columns, $number_of_table3_columns); 

您可以繼續本作中的所有表。將它放入一個函數中會很簡單,該函數接收所有列計數的數組,並返回包含每個表數據的2維數組。

+0

如果我想這樣做,我可以爲每個表單獨運行不同的查詢。 –

+0

但是,你必須做兩個查詢而不是一個。 – Barmar

+0

由於表格每個都有大約25列,所以比我自己創建數組要短。 –

0

,我想出了一個快速的解決方案:

<?php 

      $tableData = array('account'  => 'consumers', 'finance'  => 'consumers_finance', 'household'  => 'consumers_household', 'media'   => 'consumers_media', 'medical'  => 'consumers_medical', 'shopping'  => 'consumers_shopping', 'social'  => 'consumers_social', 'technology' => 'consumers_technology', 'transport'  => 'consumer_transport', 'b2b'   => 'consumers_b2b', 'employment' => 'consumer_employment_status'); 

      $openAccount = array(); 

      foreach($tableData as $key => $table) 
      { 
       $whichWhere = $db->doQuery("SHOW COLUMNS FROM `$table` LIKE 'uid'"); 
       $whichWhere = (isset($whichWhere[0]['Field'])) ? 'uid' : 'id'; 

       $getDetails = $db->getArray("SELECT * FROM $table WHERE $whichWhere = '$userID'"); 

       if(isset($getDetails[0])) 
       { 
        $openAccount[$key] = $getDetails[0]; 
       } 
       else 
       { 
        $getDetails = $db->doQuery("SHOW COLUMNS FROM `$table`"); 

        foreach($getDetails as $column) 
        { 
         $openAccount[$key][$column[0]] = ''; 
        } 
       } 
      } 

?> 

這會幫助我處理有用於流體的條目表,以便我不會必須對陣列運行雙重檢查,以避免發生不可預料的索引。