2016-03-21 68 views
0

我已經做了研究,並沒有從這方面得到任何解決方案。所以最終的想法來到Stackoverflow並提出問題。2個數組之間的PHP匹配值不同鍵

我有2個陣列象下面這樣:

BigArray

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [category_name] => Accountancy 
      [category_name_vi] => Kế toán 
      [category_id] => 1 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [category_name] => Armed forces 
      [category_name_vi] => Quân đội 
      [category_id] => 2 
     ) 

    [2] => Array 
     (
      [id] => 3 
      [category_name] => Admin & Secretarial 
      [category_name_vi] => Thư ký & Hành chính 
      [category_id] => 3 
     ) 

    [3] => Array 
     (
      [id] => 4 
      [category_name] => Banking & Finance 
      [category_name_vi] => Tài chính & Ngân hàng 
      [category_id] => 4 
     ) 
) 

和SmallArray:

Array 
(
    [0] => Array 
     (
      [id] => 7 
      [category_id] => 2 
      [jobseeker_id] => 1 
     ) 

    [1] => Array 
     (
      [id] => 8 
      [category_id] => 3 
      [jobseeker_id] => 1 
     ) 
) 

好,現在我想從SmallArray鏈路相互匹配category_id分別category_nameBigArray而輸出I只需要SmallArray和之間的匹配值其中SmallArraycategory_id是關鍵和BigArraycategory_name是像下面的值:

匹配的數組:

Array 
    (
     [0] => Array 
      (
       [2] => Armed forces      
      ) 

     [1] => Array 
      (
       [3] => Admin & Secretarial 
      ) 
    ) 

到目前爲止,我已經嘗試array_intersect,2個foreach循環,但沒有運氣。任何建議將是非常讚賞:(

感謝

回答

1

這應該這樣做:

foreach ($smallArray as $smallKey => $smallElement) { 
    foreach ($bigArray as $bigKey => $bigElement) { 
     if ($bigElement['id'] == $smallElement['category_id']) { 
      $smallArray[$smallKey] = array(
       $bigElement['id'] => $bigElement['category_name'], 
      ); 
      break; // for performance and no extra looping 
     } 
    } 
} 

這些循環後,你有你的$smallArray想要什麼

+0

完美,非常感謝你。這保存了我的生活!! – SonDang

+0

btw,這兩個數組直接從數據庫中的2個表(BigArray和SmallArray表)中獲得。你認爲我應該在smallArray表名「category_name」中添加額外的列並插入類別名稱以加快性能取而代之foreach循環像上面那樣? :) – SonDang

+1

不,不是一個好主意:)。它們是完全獨立的概念。還有其他方法可以提高性能。如果您正在從數據庫中讀取數據,那麼查詢時最好的方法是連接表(在product.category_id = category.id中)。 –

相關問題