簡體   English   中英

在PHP中如何在鍵值對匹配時將值從一個數組添加到另一個數組?

[英]How in PHP to add values from one array to another when their key value pairs match?

這是我的兩個數組:

$array1 =( [0] => Array ( [row_id] => 237 [comment] => 'hello0' )
           [1] => Array ( [row_id] => 5 [comment] => 'hello1' ) 
           [2] => Array ( [row_id] => 6 [comment] => 'hello2' ) );

$array2= ( [0] => Array ( [row_id] => 5 [vote] => 1 ) 
           [1] => Array ( [row_id] => 7 [vote] => 1 ) 
           [2] => Array ( [row_id] => 237 [vote] => 0 ) );

我想在[row_id]上匹配$array1$array2並將$array2[vote]鍵/值對添加到$ array1,其中$array1[row_id]=$array2[row_id]

這就是我想要的輸出:

$array1 =( [0] => Array ( [row_id] => 237 [comment] => 'hello0' [vote] => 0  )
           [1] => Array ( [row_id] => 5 [comment] => 'hello1' [vote] => 1 ) 
           [2] => Array ( [row_id] => 6 [comment] => 'hello2' [vote] => 1 ) );

我敢肯定有很多方法可以做到這一點,因此也希望對最快的計算方法有所了解!

foreach($array1 as $key1=>$value1)
{
  foreach($array2 as $key2=>$value2)
  {
     if($value1['row_id']==$value2['row_id'])
     {
         $value1['vote'] = $value2['vote'];
         $result[$key1][]=$value1;
     }
 }
}

$result is what you need!
foreach($array1 as $key1=>$value1)
{
    foreach($array2 as $key2=>$value2)
   {
       if($value1['row_id']==$value2['row_id'])
       {
           if ($value2['vote']) {
               $result[$key1]['vote']=$value2['vote']; // You're assigning the vote value to a new index of 'vote' on the original array.
           } else {
               $result[$key1]['vote'] = 'no vote';
           }
       }
   }
}

這是Ray Cheng答案中需要的更改。

編輯過

再次編輯:

從數據庫中提取數據時,您絕對可以將記錄作為數組獲取(查找它,就像山丘一樣古老,代碼在那里)。 下一步是將陣列重組為首選格式。 FOREACH對此非常理想。

// $array1 brought in from some other process
$arrayStorage = array();
foreach ($array1 as $row){ 
    $arrayStorage[$row['row_id']] = array('votes'=>$row['votes'], 'comment'=>$row['comment']);
}

要將其放回數據庫中時,請對其進行反轉,確保再次拉出密鑰。

foreach ($arrayStorage as $row_id=>$row_data){ ...

編輯最后:

假設兩個數據庫都已被提取為OP格式的數據...

foreach ($array1 as $row){ 
    $arrayStorage[$row['row_id']]['comment'] = $row['comment'];
}

foreach ($array2 as $row){ 
    $arrayStorage[$row['row_id']]['votes'] = $row['votes'];
}
$array1 = $arrayStorage;

// You are going through $array1 and $array2 and creating a placeholder that is built with the $row_id as an associated structure with a comment and vote for each $row_id. This is your final desired array.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM