2017-04-27 73 views
1

我有以下(簡化的)陣列:由值合併單個陣列對象,並在子陣列保持重複

$myArray = array(
    0=> array( 
     'userid' => '12', 
     'favcolor' => 'green' 
    ), 
    1=> array( 
     'userid' => '62', 
     'favcolor' => 'orange' 
    ), 
    2=> array( 
     'userid' => '12', 
     'favcolor' => 'red' 
    ), 
    3=> array( 
     'userid' => '62', 
     'favcolor' => 'blue' 
    ), 
) 

我想合併由存在的公共用戶標識值的陣列,並保持最愛顏色信息。我試過的其他方法只保留數組中的第一個favcolor值。似乎很簡單,但無法爲此找到一個快速解決方案。

預期輸出:

$myArray = array(
    0=> array( 
     'userid' => '12', 
     'favcolor' => array('green', 'red') 
    ), 
    1=> array( 
     'userid' => '62', 
     'favcolor' => array('orange', 'blue') 
    ), 
) 

這可能不與另一個數組進行比較的工作?

回答

0

這裏我們使用簡單的foreach進行合併並獲得預期結果,使用此數組的userid作爲key。這裏我們使用array_values來刪除這些密鑰。

Try this code snippet here

<?php 

ini_set('display_errors', 1); 

$myArray = array(
    0=> array( 
     'userid' => '12', 
     'favcolor' => 'green' 
    ), 
    1=> array( 
     'userid' => '62', 
     'favcolor' => 'orange' 
    ), 
    2=> array( 
     'userid' => '12', 
     'favcolor' => 'red' 
    ), 
    3=> array( 
     'userid' => '62', 
     'favcolor' => 'blue' 
    ), 
); 
$result=array(); 
foreach($myArray as $value) 
{ 
    //check for previous existence of key in resultant array 
    //if key not exist then put value on that key and using favcolor as array 
    if(!isset($result[$value["userid"]]))of key in a array. 
    { 
     $result[$value["userid"]]=array("userid"=>$value["userid"],"favcolor"=>array($value["favcolor"])); 
    } 
    //if key already exists then just adding favcolor values to that key 
    else 
    { 
     $result[$value["userid"]]["favcolor"][]=$value["favcolor"]; 
    } 
} 
print_r(array_values($result)); 

輸出:

Array 
(
    [0] => Array 
     (
      [userid] => 12 
      [favcolor] => Array 
       (
        [0] => green 
        [1] => red 
       ) 

     ) 

    [1] => Array 
     (
      [userid] => 62 
      [favcolor] => Array 
       (
        [0] => orange 
        [1] => blue 
       ) 

     ) 

) 
+0

雖然此代碼段可以解決的問題,[包括一個解釋](HTTP: //meta.stackexchange.com/questions/114762/explaining-entire基於代碼的答案)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要用解釋性註釋來擠佔代碼,這會降低代碼和解釋的可讀性! – Rizier123

+0

@ Rizier123我在添加說明 –

+0

謝謝Sahil,不得不稍微修改,因爲出現以下錯誤:「不能使用stdClass類型的對象作爲數組」。改變了代碼使用$ value-> userid而不是$ value [「userid」]並且工作得很完美。 – Sjmc11

0

只需做如下

// Creating an array for result 
foreach($myArray as $ar){ 
    if(!isset($aa[$ar['userid']])) $aa[$ar['userid']] = []; 
    if(!in_array($ar['favcolor'],$aa[$ar['userid']])) $aa[$ar['userid']][] = $ar['favcolor']; 
} 

// Designing it according to result 
foreach($aa as $arr=>$val) 
    $last[] = ['userid'=>$arr,'favcolor'=>$val]; 

echo '<pre>'; 
var_dump($last); 
+0

我們也可以在單個數組上有這個,但爲了簡單起見,我已經通過這個做了.. –