note 94910 added to ref.array

From: Date: Wed, 02 Dec 2009 11:44:17 +0000
Subject: note 94910 added to ref.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-163481@lists.php.net to get a copy of this message
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 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); ?> ---- Server IP: 69.147.83.197 Probable Submitter: 222.127.13.33 ---- Manual Page -- http://www.php.net/manual/en/ref.array.php Edit -- https://master.php.net/note/edit/94910 Del: integrated -- https://master.php.net/note/delete/94910/integrated Del: useless -- https://master.php.net/note/delete/94910/useless Del: bad code -- https://master.php.net/note/delete/94910/bad+code Del: spam -- https://master.php.net/note/delete/94910/spam Del: non-english -- https://master.php.net/note/delete/94910/non-english Del: in docs -- https://master.php.net/note/delete/94910/in+docs Del: other reasons-- https://master.php.net/note/delete/94910 Reject -- https://master.php.net/note/reject/94910 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#163481) next »