2

I have a bidimensional PHP array (matrix).

Is there anyway to extract (echo or save into another variable) a line or a column from this matrix without iterating through the elements?

Suppose we have this matrix:

A A A B
A A A C
A B C D

I want to do something like:

display_and_cut_first_line()

//Matrix after this step:    
A A A C
A B C D

display_and_cut_last_column()
//Matrix after this step:
A A A
A B C

It only has to work for marginal elements (first/last line, first/last column). I was thinking of somehow using slice, but didn't manage to do it.

4

4 回答 4

6

提取行很容易:(array_pop最后一行)和array_shift(第一行)为您执行此操作。

在 PHP 5.5 上使用array_column. 对于早期版本,必须使用array_maporarray_walk和 pop/shift 函数手动完成,依次在每一行上操作:

function extract_last_column(&$array) {
    $column = array();
    array_walk($array, function(&$row) use(&$column) {
        $column[] = array_pop($row);
    });
    return $column;
}

看到它在行动

如果需要,您可以通过使用array_slice而不是array_pop和来概括这一点array_shift——但对于这些特定的操作,它会更慢。

于 2013-06-07T08:27:15.997 回答
0
<?php 
$example = array();
$example[0][0] = 'A';$example[0][1] = 'A';$example[0][2] = 'A';$example[0][3] = 'B';
$example[1][0] = 'A';$example[1][1] = 'A';$example[1][2] = 'A';$example[1][3] = 'C';
$example[2][0] = 'A';$example[2][1] = 'B';$example[2][2] = 'C';$example[2][3] = 'D';

$example = display_and_cut_first_line($example);
print_r($example);
/* Array
(
    [0] => Array
        (
            [0] => A
            [1] => A
            [2] => A
            [3] => C
        )

    [1] => Array
        (
            [0] => A
            [1] => B
            [2] => C
            [3] => D
        )

)
 */
$example = display_and_cut_last_column($example);
print_r($example);
/* Array
(
    [0] => Array
        (
            [0] => A
            [1] => A
            [2] => A
        )

    [1] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

)
 */
function display_and_cut_first_line($array){
    array_shift($array);
    return ($array);
}

function display_and_cut_last_column($array){
    $result = array();
    foreach($array as $data):
        array_pop($data);
        $result[] = $data;
    endforeach;

    return $result;
}

?>
于 2013-06-07T08:49:06.327 回答
0

是的。要获得第一行:

$arr[0];

要获取最后一列:

$keys = array_keys($arr);
array_column($arr, end($keys));
于 2013-06-07T08:28:24.827 回答
-2

部分地。

可以使用array_splice() 剪掉一条线。

“列”在数组实现中不是可识别的条目,因此您必须至少迭代行,可能使用 array_map()。

于 2013-06-07T08:30:33.640 回答