Is there a PHP function Array Group By?

$arr1 = array('a' => '1', 'b' => 'blah', 'c' => 'whatever...',
              'aa' => '2', 'bb' => 'lbha', 'cc' => 'everwhat...', 'dd' => 'bingo',
              'aaa' => '3', 'bbb' => 'halb', 'ccc' => 'revetahw...');

In the array, I have three different index lengths a, b and c - all 1 in length. aa, bb, cc and dd have a length of 2. And aaa, bbb and ccc have a length of 3.

I am trying to find the index (group by length) with the most elements and the longest.

so I would use aa, bb, cc, dd, since they have 4 elements, this will return the length of index 2.

I want to know how can I get 2?

Here is what I am trying but not working

foreach($arr1 as $key => $data) {
   $index_length_arr[strlen($key)] = $index_length_arr[$key] + 1;
}

Results:

Array
(
    [1] => 1
    [2] => 1
    [3] => 1
)

Expected Result:

Array
(
    [1] => 3
    [2] => 4
    [3] => 3
)

Then I could see that the index (with a length of 2) had the largest number of elements:

'aa' => '2', 'bb' => 'lbha', 'cc' => 'everwhat...', 'dd' => 'bingo',
+3
source share
4 answers
$array = array_count_values(array_map('strlen',array_keys($arr1)));

Must give what you need.

Edit:

, , value =.... $index_length_arr[strlen($key)]

.

+7

( , ). - ( ):

function groupBy($array, $function)
{
    $dictionary = [];
    if ($array) {
        foreach ($array as $item) {
            $dictionary[$function($item)][] = $item;
        }
    }
    return $dictionary;
}

:

$usersByAge = groupBy($users, function ($age) { return $user->age; } );
+3

I would highly recommend using lstrojny functional-php https://github.com/lstrojny/functional-php , which includes group() function along with many other useful concepts of functional programming.

+3
source
$arr1 = array('a' => '1', 'b' => 'blah', 'c' => 'whatever...',
              'aa' => '2', 'bb' => 'lbha', 'cc' => 'everwhat...', 'dd' => 'bingo',
              'aaa' => '3', 'bbb' => 'halb', 'ccc' => 'revetahw...');


$tmpArray = array();

foreach ($arr1 AS $key => $val) {
    if (empty($tmpArray)) {
            $tmpArray[strlen($key)] = 0;
    }
    $tmpArray[strlen($key)]++;
}

print_r($tmpArray);

Gets the expected result.

0
source

Source: https://habr.com/ru/post/1772915/


All Articles