我有这个数组$输出,看起来像这样:
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
)
)
等等…
当我想删除第二个元素时,我只需使用:
$output = unset($output[1]);
获取以下内容:
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
)
)
我的问题是如何删除数组中每个元素的每第二个元素([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
)
)
不能用一个简单的命令完成,但是你可以使用一个循环:
foreach(array_keys($output) as $key) {
unset($output[$key][1]);
}
干净整洁:
$f = function(&$a,$k) { unset($a[1]); };
array_walk($arr, $f);
或:
array_walk($arr, function (&$a, $k) {
unset($a[1]);
});
您可以遍历数组,并在每个子数组中使用您想要的unset()
:
foreach($output as &$item) {
unset($item[2]);
}
unset($item); // unset reference
您将使用array_map
和array_splice
的组合:
function removeSecond( array &$arr )
{
array_splice( $arr, 1, 1 );
}
$out = array_map( 'removeSecond', $input );
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)
}
}
当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)
}
}
foreach($array as $key=>$val){ unset($val[1]); }
我用这个:
public function array_unset_key_in_children($array, $keyToUnsetInChildren)
{
$newArray = [];
foreach($array as $key=>$subArray) {
unset($subArray[$keyToUnsetInChild]);
$newArray[$key] = $subArray;
}
return $newArray;
}