用PHP连接两个关联数组 [英] Join two associative arrays with PHP

查看:110
本文介绍了用PHP连接两个关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Wordpress供稿中的数据与Google Analytics(分析)API数据合并,以创建一个Wordpress帖子信息表,其中包括每个帖子的页面浏览量。我想我可以匹配发布网址来完成此操作,但是我不确定如何执行此操作。我花了一些时间从两个来源获取数据,如下所示:

I'm trying to merge data from a Wordpress feed with Google Analytics API data to create a table of Wordpress post information including each post's page views. I think I can match on the post url to accomplish this but I am not sure how to do this. I've spent a bit of time to get the data from the two sources to look like this:

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个实例

...I have almost 2,000 instances

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 ) 
)   

我确定'key'url字段存在并且在博客供稿和Google Analytics(分析)API数据中匹配。所需的结果数组只需将 pageViews数据添加到$ blogfeed数组中的信息即可。因此

I am certain that the 'key' url field exists and matches up in both the blog feed and Google Analytics API data. The desired resulting array would simply just add the 'pageViews' data to the information in the $blogfeed array. So

[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的不同变体,并在它们之间添加了 +这两个数组变量并且没有任何运气。

I've tried different variation of array_merge, array_merge_recursive, and adding a "+" between the two array variables and have not had any luck.

任何帮助都会大为赞赏。

Any help would be greatly appreaciated.

谢谢!

推荐答案

这可以在 O(n)中完成...

This can be done in O(n), I think...

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

我没有设置php环境进行测试,但这应该可以工作。我认为没有一个命令解决方案。

I don't have a php environment set up to test but this should work. I don't think there's a "one command" solution.

这篇关于用PHP连接两个关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆