2016-08-21 61 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