2016-08-21 116 views
-3

我需要將兩個關聯數組合併爲一個。 1.第一陣列如何合併兩個關聯數組php

Array 
(
    [0] => stdClass Object 
     (
      [c_id] => 743 
      [userid] => 570c842ce6073 
      [postid] => 5761a6fb30cfa 
      [comment] => demo testing 
     ) 

); 

2.第二陣列

Array 
(
    [hip] => 120 
) 

我需要象下面

Array 
(
    [0] => stdClass Object 
     (
      [c_id] => 743 
      [userid] => 570c842ce6073 
      [postid] => 5761a6fb30cfa 
      [comment] => demo testing 
      [hip] => 120 
     ) 

); 

如何可以寫PHP代碼

+0

嗨存在,歡迎堆棧溢出...你使用鍵盤,計算機和編輯器來編寫php代碼。 :-)不,真的,這個問題太簡單了,你應該能夠自己找到答案,一旦你有所需的三個項目。例如:'$ array1 [0] - > hip = $ array2 ['hip'];',但我想你想要一個更一般的答案?看看手冊。 –

回答

0

我不喜歡它這個:

<?php 

// Object 
$object = new stdClass(); 
$object->c_id = 743; 
$object->userid = '570c842ce6073'; 
$object->comment = 'demo testing'; 

// Array containing object 
$array1[0] = $object; 

// Associative array 
$array2 = array(
    'hip' => 120, 
    'dummy1' => 100, 
    'dummy2' => 200 
); 

// Copying values from array2 to the object in array1 on key 0 
foreach($array2 as $input => $key) { 
    $array1[0]->$key = $input; 
} 

// View array1 with new values from array2 
print_r($array1); 

?> 
0

您不想在此處合併2個數組,您想要將數組鍵/值添加到對象中。

合併陣列由array_merge完成,將導致以

Array 
(
    [0] => stdClass Object 
     (
      [c_id] => 743 
      [userid] => 570c842ce6073 
      [postid] => 5761a6fb30cfa 
      [comment] => demo testing 
     ) 
    [hip] => 120 
); 

隨着代碼,你提供你要循環的第二陣列上和你第一個陣列1項插入鍵/值(這是你的對象)

$obj = $array1[0]; 
foreach($array2 as $key => $value){ 
    $obj->$key = $value; 
} 

小心,這個循環將覆蓋財產,如果它已經在陣列1