在PHP中如何从一个阵列中添加值到另一个时,他们的键值对匹配吗? [英] How in PHP to add values from one array to another when their key value pairs match?
本文介绍了在PHP中如何从一个阵列中添加值到另一个时,他们的键值对匹配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的两个数组:
$ ARRAY1 =([0] =>数组([ROW_ID] => 237 [评论] =>'hello0')
[1] =>阵列([ROW_ID] =大于5 [评论] =>'hello1')
[2] =>阵列([ROW_ID] => 6 [评论] =>'hello2'));$数组2 =([0] =>数组([ROW_ID] =大于5 [投票] => 1)
[1] =>阵列([ROW_ID] =大于7 [投票] => 1)
[2] =>阵列([ROW_ID] => 237 [投票] = 0));
我想匹配 $数组1
和 $数组2
在 [ROW_ID]的
并添加 $数组2
[投票]
键/值对$ ARRAY1其中, $数组1 [ROW_ID] = $数组2 [ROW_ID]
这是怎么想我的输出是:
$数组1 =([0] =>数组([ROW_ID] => 237 [评论] =>'hello0[投票] = 0)
[1] =>阵列([ROW_ID] =大于5 [评论] =>'hello1[投票] => 1)
[2] =>阵列([ROW_ID] => 6 [评论] =>'hello2[投票] => 1));
我敢肯定有很多方法可以做到这一点,所以在计算速度最快的想法也将是AP preciated!
解决方案
的foreach(数组1 $ $为KEY1 => $值1)
{
的foreach($数组2为$键2 => $值2)
{
如果($值1 ['ROW_ID'] == $ 2 ['ROW_ID'])
{
$值1 ['投票'] = $ 2 ['投票'];
$结果[$键1] [] = $值1;
}
}
}$结果是你需要的东西!
Here are my two arrays:
$array1 =( [0] => Array ( [row_id] => 237 [comment] => 'hello0' )
[1] => Array ( [row_id] => 5 [comment] => 'hello1' )
[2] => Array ( [row_id] => 6 [comment] => 'hello2' ) );
$array2= ( [0] => Array ( [row_id] => 5 [vote] => 1 )
[1] => Array ( [row_id] => 7 [vote] => 1 )
[2] => Array ( [row_id] => 237 [vote] => 0 ) );
I'd like to match $array1
and $array2
on [row_id]
and add $array2
's
[vote]
key/value pairs to $array1 where $array1[row_id]=$array2[row_id]
This is how I'd like the output to be:
$array1 =( [0] => Array ( [row_id] => 237 [comment] => 'hello0' [vote] => 0 )
[1] => Array ( [row_id] => 5 [comment] => 'hello1' [vote] => 1 )
[2] => Array ( [row_id] => 6 [comment] => 'hello2' [vote] => 1 ) );
I'm sure there are many ways to do this, so thoughts on the fastest computationally would also be appreciated!
解决方案
foreach($array1 as $key1=>$value1)
{
foreach($array2 as $key2=>$value2)
{
if($value1['row_id']==$value2['row_id'])
{
$value1['vote'] = $value2['vote'];
$result[$key1][]=$value1;
}
}
}
$result is what you need!
这篇关于在PHP中如何从一个阵列中添加值到另一个时,他们的键值对匹配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文