Re: Too many arrays! My head is exploding!
| From: | Florian Lemaitre | Date: | Tue, 29 May 2012 13:09:27 +0000 |
| Subject: | Re: Too many arrays! My head is exploding! | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-318016@lists.php.net to get a copy of this message | ||
Le 29/05/2012 14:45, Gary a écrit :
Okay, let's assume I have three "things", A, B, and C. I need to produce an array with a list of all possible combinations of them, however many there might be in those combinations: e.g. A, B, C, D, AB, AC, AD, BC, ABC (not sure if I've missed any!). Normally I'm pretty good at working this stuff out, but to be honest I'm struggling with this one, at least to do it in any kind of elegant way. Does anyone have any ideas? Idealy what I'd like is a multidimensional array depending on the number of "things" in the combination. Something like: array(2) { [0]=> array(3) {Enjoy ! function combinations($letters) {[0]=> array(1) { ["name"]=> string(7) "A" } [1]=> array(2) { ["name"]=> string(5) "B" } [2]=> array(2) { ["name"]=> string(4) "C" }} [1]=> array(...) {[0]=> array(2) { ["name"]=> string(13) "A+B" } [1]=> array(2) { ["name"]=> string(12) "A+C" }(etc.) --Gary Please do NOT send me 'courtesy' replies off-list.
$combinations = array(array());
foreach ($letters as $letter) {
foreach ($combinations as $combination) {
$combinations[] = array_merge($combination, array($letter));
}
}
return $combinations;
}
print"<pre>";print_r(combinations(array('a','b','c')));print"</pre>";
outputs :
Array
(
[0] => Array
(
)
[1] => Array
(
[0] => a
)
[2] => Array
(
[0] => b
)
[3] => Array
(
[0] => a
[1] => b
)
[4] => Array
(
[0] => c
)
[5] => Array
(
[0] => a
[1] => c
)
[6] => Array
(
[0] => b
[1] => c
)
[7] => Array
(
[0] => a
[1] => b
[2] => c
)
)
--
Florian Lemaitre
Développeur Web -- Cellule Edition Web/Publishing
Ligne directe : +32 69 250 554
Nos sites :
www.Potoroze.com <http://www.Potoroze.com> le portail de
shopping mode
et beauté
www.Flash-Promos.com <http://www.Flash-Promos.com>
le portail des codes
promos
_www.LaFriperieduCoin.com <http://www.LaFriperieduCoin.com>_ le
spécialiste des petites annonces mode gratuites
/Pôle Digital//, Evolution S.A/
12 rue des sablières, ZI Tournai Ouest II, 7503 Froyennes - BELGIQUE
Fax: +32 69 221 122
www.evolutioncom.eu <http://www.evolutioncom.eu>