2

I want to get most and least occuring values from php sequential/indexes, assoc and multidimensional arrays

Consider the following dataSet

        $dataSet = [
            'users' => 
            [
                'id' => 1,
                'name' => "Alex",
                'username' => 'alex',
            ],
            [
                'id' => 2,
                'name' => "Alex",
                'username' => 'alex'
            ],
            [
                'id' => 2,
                'name' => "Peter Khot",
                'username' => 'peter',
            ]
        ];

Here above are samples dataSet

Here is what that i tried

    function most_occurring(array $array, $key)
    {
        $dataSet = [];
        $i = 0;
        $keys = [];
        foreach ($array as $k) {
            if (in_array($k[$key], $keys)) {
                $keys[$i] = $k[$key];
                $dataSet[$i] = $k;
            } 

            $i++;
        }

        return $dataSet;
    }

I tried above code for most occurring values but not working at all, help me in most and least occuring values from arrays. Thanks

7
  • What if there are multiple ones with max or min occurences? Commented May 10, 2019 at 6:34
  • @Nick - the problem I have with the duplicate (unless I'm missing something) is that it doesn't work for multi-dimensional arrays ( PHP Warning: array_count_values(): Can only count STRING and INTEGER values! ). Commented May 10, 2019 at 6:38
  • Thanks @NigelRen thats why i have edit question and says Multidimensional arrays Commented May 10, 2019 at 6:38
  • by which key you want to fetch most and least occurring value? Commented May 10, 2019 at 7:00
  • @AlexJames Which key or values are most occurring? Any sample input and output examples? Commented May 10, 2019 at 7:06

2 Answers 2

1

Thanks to KIKO Software, you can still use array_count_values() for this cases. You will also need to use array_columns() and array_search() in this situation. You can refer to this link to see how array_search() helps in finding the maximum/minimum value and its corresponding key inside an array. To find the most or least occurrence, simply echo the last 6 variables that I have declared in the last 6 lines.

EDIT* reference: unset array_push

*And also, your first data in the assoc array is indexed 'user', but the second data in the assoc array is not indexed and hence it is indexed as 0.

$dataSet = [
            'users' => 
            [
                'id' => 1,
                'name' => "Alex",
                'username' => 'alex',
            ],
            [
                'id' => 2,
                'name' => "Alex",
                'username' => 'alex'
            ],
            [
                'id' => 2,
                'name' => "Peter Khot",
                'username' => 'peter',
            ]
        ];
$id = array_column($dataSet,'id');
$name = array_column($dataSet, 'name');
$username = array_column($dataSet, 'username');
$occur_id = array_count_values($id);
$occur_name = array_count_values($name);
$occur_username = array_count_values($username);
$most_occur_id  = array_search(max($occur_id),$occur_id);
$most_occur_name  = array_search(max($occur_name),$occur_name);
$most_occur_username  = array_search(max($occur_username),$occur_username);
$least_occur_id  = array_search(min($occur_id),$occur_id);
$least_occur_name  = array_search(min($occur_name),$occur_name);
$least_occur_username  = array_search(min($occur_username),$occur_username);

EDIT*: (In case of multiple highest occurence OR all same occurence, just add below code right below the above code.)

$flag = true;
$most_occur_name_list = [];
$count = 0;
while($flag)
{
  $most_occur_name_ct =  max($occur_name);
  if($most_occur_name_ct == $count || $count == 0)
    {
      array_push($most_occur_name_list,array_search($most_occur_name_ct,$occur_name));
      unset($occur_name[array_search($most_occur_name_ct,$occur_name)]);
      $count = $most_occur_name_ct;
      if(count($occur_name) == 0)
      {
          $flag = false;
          break;
      }
    }
  else
    {
      $most_occur_name_ct = $count;
      $flag = false;
      break;
    }
}

//must reinitialize the array
$occur_name = array_count_values($name);
$flag = true;
$least_occur_name_list = [];
$count = 0;
while($flag)
{
  $least_occur_name_ct =  min($occur_name);
  if($least_occur_name_ct == $count || $count == 0)
    {
      array_push($least_occur_name_list,array_search($least_occur_name_ct,$occur_name));
      unset($occur_name[array_search($least_occur_name_ct,$occur_name)]);
      $count = $least_occur_name_ct;
      if(count($occur_name) == 0)
      {
          $flag = false;
          break;
      }
    }
  else
    {
      $least_occur_name_ct = $count;
      $flag = false;
      break;
    }
}
if($most_occur_name_ct == $least_occur_name_ct)
{
    $most_occur_name_list = [];
    $least_occur_name_list = [];
}
echo "<pre>";
print_r($most_occur_name_list);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but if let consider following $most_occur_username = array_search(max($occur_username),$occur_username); if i change username values differently it always return first value, instead it should not return anything
If it has two different username with the same occurrence which is also the highest, do you plan to show multiple result also ?
yes it will be very grate, also if all of them are same then retrn nothing empty array
There is some bug for the all same occurence features, I have fix it. Please reload the page to get the latest one.
0

If you wanted to get a list of the min and max number of occurrences for just 1 element of the multidimensional array, then this code may offer a shorter method - comments in code...

$dataSet = [
    'users' =>
    [
        'id' => 1,
        'name' => "Alex",
        'username' => 'alex',
    ],
    [
        'id' => 2,
        'name' => "Alex",
        'username' => 'alex'
    ],
    [
        'id' => 2,
        'name' => "Peter Khot",
        'username' => 'peter',
    ],
    [
        'id' => 2,
        'name' => "Peter Khot",
        'username' => 'peter',
    ],
    [
        'id' => 2,
        'name' => "Paul Khot",
        'username' => 'Paul',
    ]
];

// Create an array which has the username column, but retaining the keys from
// the original array
$set = array_combine(array_keys($dataSet), 
        array_column($dataSet, "username" ));
// Summarise the values
$count = array_count_values($set);

// Get a list of the keys which match the max and min values
$minRecords = array_keys($count,min($count));
$maxRecords = array_keys($count,max($count));
// Fetch the details for the maximum value (first one returned)
$maxElements = [];
foreach ( $maxRecords as $max ) {
    $maxElements[] = $dataSet[array_search($max, $set )];
}

// Same for min values
$minElements = [];
foreach ( $minRecords as $min ) {
    $minElements[] = $dataSet[array_search($min, $set )];
}

print_r($maxElements);
print_r($minElements);

With the test data I've added, you get the output...

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alex
            [username] => alex
        )

    [1] => Array
        (
            [id] => 2
            [name] => Peter Khot
            [username] => peter
        )

)
Array
(
    [0] => Array
        (
            [id] => 2
            [name] => Paul Khot
            [username] => Paul
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.