1

I have three Classes: Table, Row, and Cell.

Table has an array of Rows and an array with order of columns.

Row has an array of Cells and Cell has textValue.

Both Table and Row implements IteratorAggregate.

My problem is that Table has an order of columns specify by the user, but when the program iterate on rows, it returns the cells in the order they were added. I tried to implement Iterator instead of IteratorAggregate but I do not know how to pass the array that table has with order of column.

I want to keep the iteration as simple as possible, with this I meant that I want to be able to foreach the Table and Row.

<?php


class Table implements \IteratorAggregate
{

    private $order;
    private $rows;

    public function __construct()
    {
        $this->rows = [];
        $this->order = [];
    }

    public function addRow(Row $row){
        array_push($this->rows, $row);
    }

    public function setOrder(Array $order){
        $this->order = $order;
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->rows);
    }
}

class Row implements \IteratorAggregate 
{
    private $cells;

    public function __construct()
    {
        $this->cells = [];
    }

    public function addCell(Cell $cell){
        array_push($this->cells, $cell);
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->cells);
    }
}

class Cell extends Model{

    public $text;

    public function __construct($text = "")
    {
        $this->text = $text;
    }
}

An example would be having a row with cells = [a,b,c]. Iterator always will give a,b,c. But the order could be specify in the table class and print something like b,c,a or c,a,b.

9
  • If data are in database, I will do sorting on db level Commented Apr 16, 2018 at 8:28
  • the problem is that the order is added in runtime by the user and it cannot be solve just ordering asc or desc Commented Apr 16, 2018 at 8:36
  • Added code and example @Yoshi. Commented Apr 16, 2018 at 8:37
  • The main problem is that table has the order and row does not know the order. Commented Apr 16, 2018 at 8:53
  • 1
    Then you'd need a custom iterator for Row that takes the order into account. Commented Apr 16, 2018 at 8:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.