PHP Array: join each sub-array together (Probability)

前端 未结 5 1621
谎友^
谎友^ 2021-01-11 18:22

I want simply to find-out better way to do this:

$array = array(
    array(\'a\', \'b\', \'c\'),
    array(\'e\', \'f\', \'g\'),
    array(\'h\', \'i\', \'j\'         


        
5条回答
  •  余生分开走
    2021-01-11 18:28

    I'm impressed about the great algorithms you guys came up with. However i think that the right method in PHP, is to use an Iterator: http://php.net/manual/fr/class.iterator.php

    I implemented an example of what you could do for your problem.

    class CombinationIterator implements Iterator {
        private $position = 0;
        private $array = array();
    
        public function __construct($array) {
            $this->array = $array;
            $this->position = array_fill(0,sizeof($this->array),0);
        }
    
        function rewind() {
            $this->position = array_fill(0,sizeof($this->array),0);
        }
    
        function current() {
            $word = array();
            foreach ($this->position as $i=>$pos) {
                $word[]=$this->array[$i][$pos];
            }
            return implode(" ",$word);
        }
    
        function key() {
            return $this->position;
        }
        function next() {
            foreach (array_reverse($this->position,true) as $i=>$pos) {
                # if position in this array has reached end, set it to 0 and increse next one
                if ($pos == sizeof($this->array[$i])-1) {
                    $this->position[$i] = 0;
                    if (array_key_exists($i-1,$this->position)) {
                        continue;
                    } else {
                        $this->rewind();
                    }
                    break;
                } else {
                    $this->position[$i]++;
                    break;
                }
    
            }
        }
        function valid() {
            $valid = false;
            foreach ($this->position as $i=>$pos) {
                if ($pos < sizeof($this->array[$i])-1) { return true; }
            }
            return $valid;
        }
    
    }
    
    

    And here is how you could use it to display your words :

    $array = array(
        array('a', 'b', 'c'),
        array('e', 'f', 'g'),
        array('h', 'i', 'j', 'k', 'l'),
        array('m', 'n', 'o', 'p', 'q', 'r', 's'),
        array('t', 'u', 'v', 'x', 'y', 'z')
    );
    
    
    $c = new CombinationIterator($array);
    while ($c->valid()) {
        echo $c->current()."\n";
        $c->next();
    }
    
    

    I didn't write the previous() method, but you can easily create it from the next() method.

    Also memory usage is very low here because you only get the position stored.

    I hope it can help you for your project.

    Bye

提交回复
热议问题