3v4l.org

run code in 300+ PHP versions simultaneously
<?php $data = array( array( "name" => "SomeName1", "type" => "A"), array( "name" => "SomeName2", "type" => "A"), array( "name" => "SomeName3", "type" => "A"), array( "name" => "SomeName4", "type" => "A"), array( "name" => "SomeName5", "type" => "A"), array( "name" => "SomeName6", "type" => "B"), array( "name" => "SomeName7", "type" => "B"), array( "name" => "SomeName8", "type" => "B"), array( "name" => "SomeName9", "type" => "C"), array( "name" => "SomeName0", "type" => "C") ); $dataSorted = array(); $counts = array(); foreach($data as $elem) { // just init values for a new type if(!isset($counts[$elem['type']])) { $counts[$elem['type']] = 0; $dataByType[$elem['type']] = array(); } // count types $counts[$elem['type']]++; // save it to grouped array $dataByType[$elem['type']][] = $elem; } // sort it to A=>5, B=>3 C=>2 arsort($counts, SORT_NUMERIC); // get sorted types as an array $types = array_keys($counts); // index will be looped 0 -> count($types) - 1 and then down to 0 again $currentTypeIndex = 0; // make a walk on sorted array. First get the most popular, then less popular etc. // when all types are added, repeat while(count($dataSorted) < count($data)) { $currentType = $types[$currentTypeIndex]; // skip adding if we ran out this type if($counts[$currentType]) { // pop an element of selected type $dataSorted[] = array_pop($dataByType[$currentType]); // decrease counter $counts[$currentType]--; } // choose next type $currentTypeIndex = (++$currentTypeIndex)%count($types); } print_r($dataSorted);
Output for 5.6.38, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.16, 8.5.0 - 8.5.1
Array ( [0] => Array ( [name] => SomeName5 [type] => A ) [1] => Array ( [name] => SomeName8 [type] => B ) [2] => Array ( [name] => SomeName0 [type] => C ) [3] => Array ( [name] => SomeName4 [type] => A ) [4] => Array ( [name] => SomeName7 [type] => B ) [5] => Array ( [name] => SomeName9 [type] => C ) [6] => Array ( [name] => SomeName3 [type] => A ) [7] => Array ( [name] => SomeName6 [type] => B ) [8] => Array ( [name] => SomeName2 [type] => A ) [9] => Array ( [name] => SomeName1 [type] => A ) )
Output for 8.3.28
/bin/php-8.3.28: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.3.28) /bin/php-8.3.28: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.3.28) /bin/php-8.3.28: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.3.28) /bin/php-8.3.28: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.3.28)
Process exited with code 1.

preferences:
131.29 ms | 408 KiB | 5 Q