我有$ array_one数组:
print_r($array_one);
Array
(
[0] => stdClass Object
(
[myid] => 653509
[date] => 2015-03-15 00:07:03
)
[1] => stdClass Object
(
[myid] => 653511
[date] => Never
)
[2] => stdClass Object
(
[myid] => 653530
[date] => 2015-03-15 02:06:26
)
然后是$ array_two;
的数组print_r($array_two);
Array
(
[0] => stdClass Object
(
[myid] => 653530
[pin] => 12fdg34345
)
[1] => stdClass Object
(
[myid] => 653509
[pin] => 1we2534dgf5
)
[2] => stdClass Object
(
[myid] => 653511
[pin] => 12wer3u45
)
然后我想根据具有相同值的键合并它,其中预期的结果是:
Array
(
[0] => stdClass Object
(
[myid] => 653530
[pin] => 12fdg34345
[date] => 2015-03-15 02:06:26
)
[1] => stdClass Object
(
[myid] => 653509
[pin] => 1we2534dgf5
[date] => 2015-03-15 00:07:03
)
[2] => stdClass Object
(
[myid] => 653511
[pin] => 12wer3u45
[date] => Never
)
从上面的结果中,first_array中的date
数组键被推送到
second_array基于my_id
键的类似值。
有办法做到这一点吗?
请帮忙,非常感谢您的帮助。
干杯!
答案 0 :(得分:2)
根据我的评论,此解决方案取决于结构稍微变化,是关联数组的数组,而不是对象数组。正如你所说的那样,数据来自(a)数据库,如果你使用像PDO这样的东西,这只是意味着设置正确的提取模式的一个小改动。
结果可以通过组合php内置函数array_column
和array_replace_recursive
来实现。如果您希望结果数组仍为0索引,我们也可以使用array_values
。
$array_one = [
[
'myid' => 653509,
'date' => '2015-03-15 00:07:03'
],
[
'myid' => 653511,
'date' => 'Never'
],
[
'myid' => 653530,
'date' => '2015-03-15 02:06:26'
]
];
$array_two = [
[
'myid' => 653530,
'pin' => '12fdg34345'
],
[
'myid' => 653509,
'pin' => '1we2534dgf5'
],
[
'myid' => 653511,
'pin' => '12wer3u45'
]
];
$merged = array_replace_recursive(
array_column($array_one, null, 'myid'),
array_column($array_two, null, 'myid')
);
答案 1 :(得分:1)
<?php
$temp_arr_one = array();
foreach($array_one as $key1=>$val1){
$temp_arr_one[$val1['myid']] = $val1->date;
}
$final_arr = array();
foreach($array_two as $key2=>$val2){
$final_arr[$key2]['myid'] = $val2->myid;
$final_arr[$key2]['pin'] = $val2->pin;
$final_arr[$key2]['date'] = $temp_arr_one[$val2->myid];
}
print_r($final_arr);
?>