问题
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); returns:
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 )
)
...I have almost 2,000 instances
print_r($blogfeed); returns
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 )
)
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 )
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.
Thanks!
回答1:
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;
}
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.
来源:https://stackoverflow.com/questions/13575576/join-two-associative-arrays-with-php