Is there a PHP Array Group By function?
$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 are all 1 in length. aa,bb,cc and dd are all 2 in length. And aaa,bbb and ccc are all 3 in length.
What I'm trying to do is find the index (group by len开发者_开发知识库gth) with the most elements and the greatest length.
so I would use aa,bb,cc,dd as they have 4 elements, this would return the index length of 2.
I want to know how I can get the 2?
Here is what I'm trying but it's 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 Output:
Array
(
[1] => 3
[2] => 4
[3] => 3
)
Then I could see that index (with the length of 2) had the most elements:
'aa' => '2', 'bb' => 'lbha', 'cc' => 'everwhat...', 'dd' => 'bingo',
$array = array_count_values(array_map('strlen',array_keys($arr1)));
Should give ya what ya want.
Edit:
Your original code was fine except you have to change the = .... to $index_length_arr[strlen($key)]
You were using two different keys.
I'd recommend creating your own (or using a library that already does it). It'd be something like this (did not test it):
function groupBy($array, $function)
{
$dictionary = [];
if ($array) {
foreach ($array as $item) {
$dictionary[$function($item)][] = $item;
}
}
return $dictionary;
}
Using it like this:
$usersByAge = groupBy($users, function ($age) { return $user->age; } );
I would highly recommend using lstrojny's functional-php https://github.com/lstrojny/functional-php which includes a group()
function along with a host of other useful functional programming concepts.
$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 you your expected result.
精彩评论