如何在php中合并两个关联数组

时间:2016-08-21 10:11:28

标签: php arrays associative-array

我需要将两个关联数组合并为一个。 1.第一阵列

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代码

2 个答案:

答案 0 :(得分: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);

?>

答案 1 :(得分: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;
}

小心,如果属性已存在于array1

中,则此循环将覆盖该属性