note 94910 deleted from ref.array by levim
| From: | levim@php.net | Date: | Tue, 06 May 2014 22:01:42 +0000 |
| Subject: | note 94910 deleted from ref.array by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199444@lists.php.net to get a copy of this message | ||
Note Submitter: phektus at gmail dot com
----
This is how I solved my array combinations problem. My particular situation is that I needed to
project combinations of certain results and analyse each combination based from a consolidation of
one of their attributes. The following example does not show the analysis part but it shows how I
came up with my combinations ($traits).
This is actually an improvement on: http://ask.metafilter.com/64554/Finding-combinations-in-PHP
as it deals with arrays of strings, while I need to combine arrays within an array (you guessed it,
database results).
Hope somebody finds this useful or teaches me a simpler way [by email] to do this. Public domain
etc.
<?php
header('Content-Type: text/plain');
class Test {
// holds the combinations
var $combinations= array();
function getCombinations($batch, $elements, $i) {
if ($i >= count($elements)) {
$this->combinations[] = $batch;
} else {
foreach ($elements[$i] as $element) {
$this->getCombinations(array_merge($batch, $element), $elements, $i + 1);
}
}
}
}
// Test it!
$traits = array (
array(
array('Happy'),
array('Sad'),
array('Angry'),
array('Hopeful')
),
array(
array('Outgoing'),
array('Introverted')
),
array(
array('Tall'),
array('Short'),
array('Medium')
),
array(
array('Violent'),
array('Quiet'),
array('Psychotic')
),
array(
array('Handsome'),
array('Plain'),
array('Ugly')
)
);
$test = new Test();
$start = array();
$test->getCombinations($start, $traits, 0);
print_r($test->combinations);
?>