Created
December 13, 2019 16:05
-
-
Save josecanhelp/9574f84ecb10171c03e10e41fd910fc9 to your computer and use it in GitHub Desktop.
Cartesian Grouping
This file contains 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 | |
function inject($elem, $array) | |
{ | |
return array_map(function ($n) use ($elem) { | |
return array_merge((array) $elem, (array) $n); | |
}, $array); | |
} | |
function zip($array1, $array2) | |
{ | |
return array_reduce( | |
$array1, | |
function ($v, $n) use ($array2) { | |
return array_merge($v, inject($n, $array2)); | |
}, | |
array() | |
); | |
} | |
function cartesian_product($array) | |
{ | |
$keys = array_keys($array); | |
$prod = array_shift($array); | |
$prod = array_reduce($array, 'zip', $prod); | |
return array_map(function ($n) use ($keys) { | |
return array_combine($keys, $n); | |
}, $prod); | |
} | |
function getPrice($loans, $credit) | |
{ | |
// some logic | |
return 100; | |
} | |
$loans = ['mortgage', 'car']; | |
$credits = ['good', 'bad']; | |
$amount = ['1000', '2000']; | |
$random = ['yes', 'no']; | |
$all = [$loans, $credits, $amount, $random]; | |
collect(cartesian_product($all)) | |
->mapToGroups(function ($dict) { | |
$group = array_shift($dict); | |
$subKey = implode('-', $dict); | |
return [ | |
$group => [ | |
$subKey => getPrice(...$dict) | |
] | |
]; | |
}) | |
->map(function ($values) { | |
return array_merge(...$values); | |
}) | |
->toArray(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment