Created
March 17, 2016 19:25
-
-
Save colindecarlo/ce00494c1460b7f082d7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$data = array_map(function ($elem) { | |
return ['elem' => $elem, 'nested' => []]; | |
}, [1, 2, 2, 3, 4, 1, 2, 1, 1, 2, 2]); | |
function group($data) { | |
$subs = false; | |
$data = array_chunk($data, 2); | |
$results = []; | |
foreach ($data as $chunk) { | |
if (count($chunk) == 1) { | |
$results[] = $chunk[0]; | |
} else { | |
$nested = nest($chunk); | |
$subs = $subs || count($nested) == 1; | |
$results = array_merge($results, $nested); | |
} | |
} | |
return $subs ? group($results) : $results; | |
} | |
function nest($chunk) { | |
if (count($chunk[0]['nested']) && array_search($chunk[1]['elem'], array_column($chunk[0]['nested'], 'elem')) !== false) { | |
$chunk[0]['nested'][] = $chunk[1]; | |
return [$chunk[0]]; | |
} | |
if ($chunk[1]['elem'] <= $chunk[0]['elem']) { | |
return $chunk; | |
} | |
if (count($chunk[0]['nested']) == 0) { | |
$chunk[0]['nested'][] = $chunk[1]; | |
return [$chunk[0]]; | |
} | |
$nested = end($chunk[0]['nested']); | |
while (is_array($nested)) { | |
$result = nest([$nested, $chunk[1]]); | |
if (count($result) == 1) { | |
return [$chunk[0]]; | |
} | |
$nested = end($nested['nested']); | |
} | |
return $chunk; | |
} | |
var_dump(group($data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment