Search code examples
phparraysoptimizationcountstore

How to PROPERLY store duplicate keys of array


$statues is an array of multiple objects from a twitter api response.

$status->retweeted_status->user->screen_name is the username of a Twitter account.

$status->retweeted_status->user->profile_image_url_https is the image from that user.

What I want is:

  1. Store username
  2. Store image URL
  3. COUNT how many times does this user repeats.

As I know, is not possible to have repeated keys into asocciative array, So i wrote down this code:

$vector = [];

foreach($statuses as $status ){
      
        if(array_key_exists ( $status->retweeted_status->user->screen_name ,$vector)){
            $vector[$status->retweeted_status->user->screen_name]['cont'] = $vector[$status->retweeted_status->user->screen_name]['cont'] + 1;
        
        } else{
            $vector[$status->retweeted_status->user->screen_name] = array(
                'img' => str_replace('_normal','_400x400',$status->retweeted_status->user->profile_image_url_https),
                'cont' => 1
            );
        }
      


    }

The result is the following: enter image description here

That's okay, but I want to know:

  1. Is there a better way to Store username, image, and also count how many times does this user appears (Optimize my code)?

  2. How can I order the array to show FIRST the user with most repetitions and last the user with less (Descendent) ?

Thank you!!


Solution

  • To count the User I think what you're looking for is here: Count occurrence of duplicate items in array

    Basically use array_count_values. There's other built in array functions that will order your array for you if needed.