views:

446

answers:

3

I have a 2-D array of integers. I'd like to initialize it in column order, and then access it in row order. Is it possible to initialize in PHP in column order without explicitly iterating over every row?

For example, in R, one can do

my2d = matrix(nrow=2, ncol=2)  # create 2x2 matrix
my2d[,1] = c("a","c")  # initialize column 1 in a single statement
my2d[,2] = c("b","d")  # initialize column 2 in a single statement
print(my2d[1,])        # returns "a" "b"
print(my2d[2,])        # returns "c" "d"
A: 

Unfortunately, no. A 2-D array of integers in PHP is actually set up as an array of rows, each row being an array of columns. You could, in theory do something like:

 $data[0][1];
 $data[1][1];

but that is really just iterating. It seems (and I have very little knowledge of R, so excuse me if I'm correct), that R's implementation of a matrix is an actual, true to form, multi-dimensional array. They're really not compatible.

Michael T. Smith
This confirms my impression, too. I had been hoping to be proven wrong!
Jack Tanner
A: 

Hi,

What about something like this :

$tab = array(
    array('a', 'b'), // first line
    array('c', 'd'), // second line
);
var_dump($tab);

Which gives you :

array
  0 => 
    array
      0 => string 'a' (length=1)
      1 => string 'b' (length=1)
  1 => 
    array
      0 => string 'c' (length=1)
      1 => string 'd' (length=1)

Only one statement, and no iteration ;-)

It's declared as a whole, and not really "column by column", ; one might say it's declared line by line, and not column by column -- which is not quite possible in PHP... But it seems to fit your needs ?

Pascal MARTIN
This is initialization in row order, which is exactly what I'm trying to avoid. :)
Jack Tanner
A: 

I'd suggest entering data in row order and writing a function to read off "columns" as you need them.

function col($arr, $offs) {
    $t = array();

    foreach($arr as $row)
        $t[]= $row[$offs];

    return $t;
}

$my2d  = array();
$my2d[]= array("a", "c");
$my2d[]= array("b", "d");
print(col($my2d,0));       // returns array("a","b")
print(col($my2d,1));       // returns array("c","d")

Edit: If you want to be pedantic, you could write the function to enter your data in column order and then read it off in row order; it makes no real difference except it will screw your data up if you ever vary the number of data items in a column.

In any event, the answer is: No, somewhere you're going to have to iterate.

Hugh Bothwell
That's the opposite of what I'm looking for, namely initialization in column order and row-order reading.
Jack Tanner