用PHP加入两个关联数组

时间:2012-11-27 00:32:53

标签: arrays array-merge

我正在尝试将Wordpress Feed中的数据与Google AnalyticsAPI数据合并,以创建Wordpress帖子信息表,包括每个帖子的页面浏览量。我想我可以匹配帖子网址来完成这个但我不知道该怎么做。我花了一些时间从这两个来源获取数据:

print_r($ analytics); 返回:

Array ( 
 [0] => Array ( 
  [url] => blog-post-url-121 
  [pageViews] => 34326 ) 
 [1] => Array ( 
  [url] => blog-post-url-245 
  [pageViews] => 14642 ) 
 [2] => Array ( 
  [url] => blog-post-url-782
  [pageViews] => 13201 )
 )  

......我有近2,000个实例

print_r($ blogfeed); 返回

Array ( 
 [0] => Array ( 
  [url] => blog-post-url-457
  [PostID] => 87249 
  [Date] => 2012-11-26 15:58:45 
  [Author] => John-Smith 
  [Title] => Blog Post Title #457
  [Categories] => Dining, News ) 
 [1] => Array ( 
  [url] => blog-post-url-245
  [PostID] => 88148 
  [Date] => 2012-11-26 15:00:20 
  [Author] => Mary-Jones 
  [Title] => Blog Post Title #245
  [Categories] => Events, Nightlife ) 
)   

我确定“关键”网址字段存在,并且在博客Feed和Google AnalyticsAPI数据中都匹配。所需的结果数组只是将'pageViews'数据添加到$ blogfeed数组中的信息。所以

[1] => Array ( 
 [url] => blog-post-url-245
 [PostID] => 88148 
 [Date] => 2012-11-26 15:00:20 
 [Author] => Mary-Jones 
 [Title] => Blog Post Title #245
 [Categories] => Events, Nightlife
 [pageViews] => 14642 ) 

我尝试了不同的array_merge变体,array_merge_recursive,并在两个数组变量之间添加了一个“+”,但没有运气。

任何帮助都会有很大的帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

这可以在O(n)中完成,我认为......

foreach ($analytics as $viewElement) {
    $viewAssoc[$viewElement['url']] = $viewElement['pageViews'];
}
foreach ($blogfeed as $index => $blogElement) {
    $blogElement['pageViews'] = $viewAssoc[$blogElement['url']];
    $newBlogfeed[$index] = $blogElement;
}

我没有设置测试的PHP环境,但这应该工作。我不认为有一个“一个命令”的解决方案。