简体   繁体   中英

column access with multidimensional array in php

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"

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.

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 ?

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.

Have you thought about using array_map()? Eg

$my2d = array_map(function($row,$col) {
            $row[1]=$col;return $row;
        }, $my2d, array('a','c'));

It's an iteration, but well hidden ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM