2013-04-13 72 views
0

用戶定義的數組我有2個數組合併成一個陣列,對於我曾嘗試 -合併2個在PHP

$TotalResult = array_merge_recursive($arr1, $arr2); 

但我沒有得到這個功能所期望的結果。

我2個陣列:

$arr1 = Array(
[0] => Array 
    (
     [search_terms] => facebook 
     [search_count] => 1 
    ) 

[1] => Array 
    (
     [search_terms] => yahoomail.com 
     [search_count] => 1 
    ) 

[2] => Array 
    (
     [search_terms] => google.com 
     [search_count] => 1 
    ) 

[3] => Array 
    (
     [search_terms] => rediff.com 
     [search_count] => 2 
    ) 
); 

$arr2=Array(
[0] => Array 
    (
     [search_terms] => youtube 
     [adclicks_count] => 1 
    ) 

[1] => Array 
    (
     [search_terms] => hotmail 
     [adclicks_count] => 4 
    ) 

[2] => Array 
    (
     [search_terms] => facebook 
     [adclicks_count] => 2 
    ) 

[3] => Array 
    (
     [search_terms] => google.com 
     [adclicks_count] => 3 
    ) 

[4] => Array 
    (
     [search_terms] => yahoomail 
     [adclicks_count] => 1 
    ) 

[5] => Array 
    (
     [search_terms] => stackoverflow 
     [adclicks_count] => 1 
    ) 
); 

而且我想要的結果數組3如下 -

$arr3 = Array(
[0] => Array 
    (
     [search_terms] => facebook 
     [search_count] => 1 
    [adclicks_count] => 2 
    ) 

[1] => Array 
    (
     [search_terms] => yahoomail.com 
     [search_count] => 1 
     [adclicks_count] => 1 
    ) 

[2] => Array 
    (
     [search_terms] => google.com 
     [search_count] => 1 
     [adclicks_count] => 3 
    ) 

[3] => Array 
    (
     [search_terms] => rediff.com 
     [search_count] => 2 
     [adclicks_count] => 0 
    ) 

[4] => Array 
    (
     [search_terms] => youtube 
     [search_count] => 0 
     [adclicks_count] => 1 
    ) 

[5] => Array 
    (
     [search_terms] => hotmail 
     [search_count] => 0 
     [adclicks_count] => 4 
    ) 
[6] => Array 
    (
     [search_terms] => stackoverflow 
     [search_count] => 0 
     [adclicks_count] => 1 
    ) 
); 

請給我建議的,如果在PHP提供的解決方案。

+0

在你想要的數組,你是如何計算'adclicks_count'?它似乎相當武斷。 – Jon

+0

目前還不清楚你想如何合併它們。但是由於您在不同的數組索引中使用了搜索詞,因此'array_merge'不是您需要的,您必須將它與自定義函數合併 – Uby

+0

抱歉,Jon剛糾正了我的數組。 – user1045052

回答

0

一個簡單的自定義腳本可以使招工作

http://www.tehplayground.com/#7Uudu9PwY

$arr1 = array(
    array('search_terms' => 'facebook', 'search_count' => 1), 
    array('search_terms' => 'whatever', 'search_count' => 4) 
); 


$arr2 = array(
    array('search_terms' => 'facebook', 'adclicks_count' => 2), 
    array('search_terms' => 'whatever', 'adclicks_count' => 3) 
); 


$searchTermToData = array(); 

foreach ($arr1 as $element) 
    $searchTermToData[$element['search_terms']] = $element; 

foreach ($arr2 as $element) 
    $searchTermToData[$element['search_terms']]['adclicks_count'] = $element['adclicks_count']; 

// build result 

$result = array_values($searchTermToData); 
+0

你的代碼並不完全完美,但它幫助我獲得了正確的解決方案,並且網站http://www.tehplayground.com也非常有用。 – user1045052