|
Posted by sberry on 11/12/59 12:00
On Jan 16, 10:04 am, Toby A Inkster <usenet200...@tobyinkster.co.uk>
wrote:
> sberry wrote:
> > $a = array('big', 'small', 'medium');
> > $b = array('old', 'new');
> > $c = array('blue', 'green');
>
> > I want to take those and end up with all of the combinations they create
> > like the following
>
> The previews of Perl6 are delicious in this area.
>
> @a = 'big', 'small', 'medium';
> @b = 'old', 'new';
> @c = 'blue', 'green';
>
> @combos = @a X,X @b X,X @c;
>
> And there, @combos is a list of arrays, with each of the arrays being
> something like ('big', 'new', 'blue'). It's got really great functions for
> operating on whole data structures in one fell swoop.
>
> Back to the real world of PHP 5 though. The easiest way is to use a
> handful of well-placed foreach loops:
>
> $a = array('big', 'small', 'medium');
> $b = array('old', 'new');
> $c = array('blue', 'green');
> $combos = array();
>
> foreach ($a as $x) foreach ($b as $y) foreach ($c as $z)
> {
> $combos[] = array($x, $y, $z);
> }
>
> print_r($combos);
>
> --
> Toby A Inkster BSc (Hons) ARCS
> [Geek of HTML/SQL/Perl/PHP/Python/Apache/Linux]
> [OS: Linux 2.6.17.14-mm-desktop-9mdvsmp, up 17 days, 5:00.]
>
> Gnocchi all'Amatriciana al Forno
> http://tobyinkster.co.uk/blog/2008/01/15/gnocchi-allamatriciana/
ZeldorBlat:
Thanks for the info. I was trying to do something other than nested
foreach loops, but that seems to be the PHP way to do it.
Toby:
Perl6 does indeed seem to have some really nice features... but
project was developed in PHP (not my choice).
I am used to Python which has a very elegant solution as well using
"List Comprehensions" like so:
a = ['big', 'small', 'medium']
b = ['old', 'new']
c = ['blue', 'green']
d = [[i,j,k] for i in a for j in b for k in c]
print d
[['big', 'old', 'blue'], ['big', 'old', 'green'], ['big', 'new',
'blue'], ['big', 'new', 'green'], ['small', 'old', 'blue'], ['small',
'old', 'green'], ['small', 'new', 'blue'], ['small', 'new', 'green'],
['medium', 'old', 'blue'], ['medium', 'old', 'green'], ['medium',
'new', 'blue'], ['medium', 'new', 'green']]
:)
Navigation:
[Reply to this message]
|