doudun1029 2017-05-23 16:44
浏览 150
已采纳

PHP将多个数组组合成多维数组

I am writing code in PHP to collect all the hashtags which I've used in all my media posts and see in how many posts I've used the hashtag and how many likes the post with that hashtag received in total.

I have collected all of the media posts in my database and are now able to export this information. Here is an example of the multidimensional array which is being output:

Array
(
    [0] => Array
        (
            [id] => 1
            [caption] => #londra #london #london_only #toplondonphoto #visitlondon #timeoutlondon #londres #london4all #thisislondon #mysecretlondon #awesomepix #passionpassport #shootermag #discoverearth #moodygrams #agameoftones #neverstopexploring #beautifuldestinations #artofvisuals #roamtheplanet #jaw_dropping_shots #fantastic_earth #visualsoflife #bdteam #nakedplanet #ourplanetdaily #earthfocus #awesome_earthpix #exploretocreate #londoneye
            [likesCount] => 522
        )

    [1] => Array
        (
            [id] => 2
            [caption] => #londra #london #london_only #toplondonphoto #visitlondon #timeoutlondon #londres #london4all #thisislondon #mysecretlondon #awesomepix #passionpassport #shootermag #discoverearth #moodygrams #agameoftones #neverstopexploring #beautifuldestinations #artofvisuals #roamtheplanet #jaw_dropping_shots #fantastic_earth #visualsoflife #bdteam #nakedplanet #ourplanetdaily #earthfocus #awesome_earthpix #harrods #LDN4ALL_One4All
            [likesCount] => 1412
        )
)

I am able to separate these hashtags out using the following function:

function getHashtags($string) {  
    $hashtags= FALSE;  
    preg_match_all("/(#\w+)/u", $string, $matches);  
    if ($matches) {
        $hashtagsArray = array_count_values($matches[0]);
        $hashtags = array_keys($hashtagsArray);
    }
    return $hashtags;
}

Now I want to create a multidimensional array for each hashtag which should look like this:

Array
(
    [0] => Array
    (
        [hash] => #londra
        [times_used] => 2
        [total_likes] => 153
    )
    [1] => Array
    (
        [hash] => #london
        [times_used] => 12
        [total_likes] => 195
    )
)

I am quite new to this and not sure how to achieve this. Help and suggestions are appreciated!

  • 写回答

1条回答 默认 最新

  • doulian4467 2017-05-23 18:29
    关注

    It would be easier to use the hashtags as keys in your array. You can transform it later to your final format if you want to. The idea is to traverse your input array and within each element iterate on the given hashtags string, increasing counters.

    And if your hashtags are always in a string like that, separated by whitespace, you can also get an array of then with explode() or preg_split() for finer control.

    $posts = # your input array
    $tags = [];
    
    foreach ($posts as $post) {
        $hashtags = explode(' ', $post['caption']);
        foreach ($hashtags as $tag) {
            if (!key_exists($tag, $tags)) {
                # first time seeing this one, initialize an entry
                $tags[$tag]['counter'] = 0;
                $tags[$tag]['likes'] = 0;
            }
            $tags[$tag]['counter']++;
            $tags[$tag]['likes'] += $post['likesCount'];
        }
    }
    

    Transforming to something closer to your original request:

    $result = array_map(function($hashtag, $data) {
        return [
            'hash' => $hashtag,
            'times_used' => $data['counter'],
            'total_likes' => $data['likes'],
            'average_likes' => $data['likes'] / $data['counter'],
        ];
    }, array_keys($tags), $tags);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器