删除“列"的最佳方法来自多维数组 [英] Best way to delete "column" from multidimensional array

查看:21
本文介绍了删除“列"的最佳方法来自多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维的 php 数组来表示这样的表

I have a multidimensional php array that represents a table like this

-------------
| A | 0 | A |
|---|---|---|
| 0 | 0 | 0 |
|---|---|---|
| A | 0 | A |
-------------

所以数组看起来像这样:

so the array looks like this:

array (size=3)
  0 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string '0' (length=1)
      2 => string 'A' (length=1)
  1 => 
    array (size=3)
      0 => string '0' (length=1)
      1 => string '0' (length=1)
      2 => string '0' (length=1)
  2 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string '0' (length=1)
      2 => string 'A' (length=1)

现在我想删除第二行和第二列(顺便说一句,这只是一个简化的例子).
删除行很容易:

Now i want to delete the second row and the second column (this is just a simplified example btw).
Deleting the row is easy:

array_splice($array, 1, 1);

我发现了这种方法但是想知道是否有更简单的方法(类似于行)来删除列?也许先转置数组?

I found this approach but was wondering if there was a simpler way (similar to the row) of deleting the column as well? Maybe transposing the array first?

推荐答案

试试这个:

function delete_row(&$array, $offset) {
    return array_splice($array, $offset, 1);
}

function delete_col(&$array, $offset) {
    return array_walk($array, function (&$v) use ($offset) {
        array_splice($v, $offset, 1);
    });
}

在 Ideone 上测试:http://ideone.com/G5zRi0

Tested on Ideone: http://ideone.com/G5zRi0

编辑(Amade):

delete_col 函数也可以稍微修改以处理缺少列的数组:

delete_col function can also be slightly modified to work with arrays with missing columns:

function delete_col(&$array, $key) {
    return array_walk($array, function (&$v) use ($key) {
        unset($v[$key]);
    });
}

这可以用于例如当您需要遍历数组并在每一步中删除一些列时.使用 array_splice 而不是 unset 的函数在这种情况下是不合适的(它基于偏移量而不是基于键).

This can be used e.g. when you need to iterate over an array and remove some columns in each step. A function using array_splice instead of unset would not be appropriate in such scenarios (it's offset-based and not key-based).

这篇关于删除“列"的最佳方法来自多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆