我需要将两个关联数组合并为一个。
第一个数组
Array
(
[0] => stdClass Object
(
[c_id] => 743
[userid] => 570c842ce6073
[postid] => 5761a6fb30cfa
[comment] => demo testing
)
);
第二个数组
Array
(
[hip] => 120
)
我需要像下面这样的
Array
(
[0] => stdClass Object
(
[c_id] => 743
[userid] => 570c842ce6073
[postid] => 5761a6fb30cfa
[comment] => demo testing
[hip] => 120
)
);
如何编写所需的 PHP 代码?
我会这样做:
<?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);
?>
您不想在这里合并 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 中,则此循环将覆盖该属性