PHP - 在多维数组中取消设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7260468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - unset in a multidimensional array
提问by Giel
I have this array $output which looks like this:
我有这个数组 $output 看起来像这样:
Array(
[0] => Array(
[0] => 1a
[1] => 1b
[2] => 1c
)
[1] => Array(
[0] => 2a
[1] => 2b
[2] => 2c
)
[2] => Array(
[0] => 3a
[1] => 3b
[2] => 3c
)
[3] => Array(
[0] => 4a
[1] => 4b
[2] => 4c
)
)
and so on...
等等...
When I want to remove the second element I just use
当我想删除第二个元素时,我只使用
$output = unset($output[1]);
to get the following:
得到以下内容:
Array(
[0] => Array(
[0] => 1a
[1] => 1b
[2] => 1c
)
[1] => Array(
[0] => 3a
[1] => 3b
[2] => 3c
)
[2] => Array(
[0] => 4a
[1] => 4b
[2] => 4c
)
)
My question is how to remove every second element of every element in the array ([0][1], [1][1], [2][1], [3][1] ,...) to get the following:
我的问题是如何删除数组中每个元素的第二个元素 ([0][1], [1][1], [2][1], [3][1] ,...) 以获得下列:
Array(
[0] => Array(
[0] => 1a
[1] => 1c
)
[1] => Array(
[0] => 2a
[1] => 2c
)
[2] => Array(
[0] => 3a
[1] => 3c
)
[3] => Array(
[0] => 4a
[1] => 4c
)
)
回答by Marc B
Can't be done with a simple command, but you can use a loop:
不能用一个简单的命令来完成,但你可以使用一个循环:
foreach(array_keys($output) as $key) {
unset($output[$key][1]);
}
回答by Arnaud Le Blanc
You can iterate over the array, and unset()
what you want in each sub-array:
您可以遍历数组,以及unset()
每个子数组中所需的内容:
foreach($output as &$item) {
unset($item[2]);
}
unset($item); // unset reference
回答by dnagirl
Clean and neat:
干净整洁:
$f=function(&$a,$k) { unset $a[1]; };
array_walk($arr,$f);
回答by FabioG
foreach($array as $key=>$val){ unset($val[1]); }
回答by cwallenpoole
You'd use a combination of array_map
and array_splice
:
你会使用的组合array_map
和array_splice
:
function removeSecond( array &$arr )
{
array_splice( $arr, 1, 1 );
}
$out = array_map( 'removeSecond', $input );
The problem with unset
is that it will leave the indexes as they were:
问题unset
在于它会使索引保持原样:
$ php -r '$arr = array(array(0,1,2)); unset($arr[0][1]); var_dump($arr);'
array(1) {
[0]=>
array(2) {
[0]=>
int(0)
[2]=>
int(2)
}
}
While splice will update the indexes:
虽然 splice 将更新索引:
$ php -r '$arr = array(array(0,1,2)); array_splice($arr[0], 1, 1); var_dump($arr);'
array(1) {
[0]=>
array(2) {
[0]=>
int(0)
[1]=>
int(2)
}
}