Column access with multidimensional array in php

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

For example, in R you 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"

      

+2


source to share


4 answers


Unfortunately no. A 2-dimensional array of integers in PHP is actually configured as an array of strings, each row is an array of columns. You could theoretically do something like:

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


but this is really just a repetition. It seems (and I have very little knowledge of R, so excuse me if I'm right) that the R implementation of a matrix is ​​an actual, true form, multidimensional array. They are really incompatible.

0


source


Something like that:

$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 is declared as an integer, not column by column; it can be said to be declared line by line, not column by column, which is not entirely possible in PHP ... But it seems to suit your needs?

0


source


I would suggest entering the data in row order and writing a function to read the "columns" as needed.

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 can write a function to enter your data in column order and then read it in row order; it makes no real difference, except that it will twist your data if you ever change the number of data items in the column.

In any case, the answer is: No, somewhere you have to repeat.

0


source


Have you thought about using array_map ()? For example.

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

      

This is an iteration but well hidden;)

0


source







All Articles