php - Multi-Dimensional Array Formatting -
i'm working on personal project create keyword generating tool. have setup recursive function loop through multi-dimensional array find out possible combinations in supplied list of keywords.
public function recurseful($start, $args) { if (is_array($args)) { foreach ($args[0] $value) { $this->output[] = trim("{$start} {$value}"); if (count($args) > 1) { $this->recurseful($value, array_slice($args, 1)); } } } return; }
i'm passing in:
$data = array( array('new york', 'new york city'), array('hotel', 'lodging','motel'), ); $results = recurseful('', $data);
it iterates through , gives me list of various keyword combinations. however, it's returning them in single array of $output. function designed take values $data[0] (or rather $args[0]) , match them other keywords given.
i'd rather them returned
1st ('new york', 'new york city') 2nd ('new york hotel', 'new york lodging', 'new york motel') 3rd ('new york city hotel', 'new york city lodging', 'new york city motel')
it returns of matches one. how make them go different array? being 1st exact match of $data[0]
, easy to, how force new array after looping through possible combinations 1 value in $data[0]
? (so if there 3 values in $data[0]
, there 3 additional arrays returned).
screenshots user enter desired word choices spreadsheet.
results returned similar this. i'd put each column of data it's own array. current solution above puts own array, therefore returned in same column.
i have arrived on working solution after more thought & coworkers.
function permutate($data, $limit){ $this->limit = $limit; $this->data = $data; $this->numlevels = count($this->data); $this->possiblepermutations = 1; foreach ($this->data $array){ $this->possiblepermutations *= count($array); } ($i = 0; $i < $this->numlevels - 0; $i++){ $this->permutations[$i] = array(); } $this->recurse(0, 0, ''); return $this->permutations; } private function recurse($currentlevel, $level, $string){ if ($this->numperms == $this->limit) return; foreach ($this->data[$level] $val){ if ($this->numperms == $this->limit) return; $newstring = "$string $val"; if ($level == $currentlevel){ $this->permutations[$level][] = trim($newstring); $this->numperms++; } if ($level < $this->numlevels - 1 , $level <= $currentlevel){ $this->recurse($currentlevel, $level + 1, $newstring); } } if (! $level , $currentlevel < $this->numlevels){ $this->recurse($currentlevel + 1, 0, ''); } }
this gives me desired results.
Comments
Post a Comment