15

我有这个数组 $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
    )
)

等等...

当我想删除第二个元素时,我只使用:

$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
    )
)
4

6 回答 6

23

不能用一个简单的命令来完成,但你可以使用循环:

foreach(array_keys($output) as $key) {
   unset($output[$key][1]);
}
于 2011-08-31T16:46:28.373 回答
8

您可以遍历数组以及unset()每个子数组中所需的内容:

foreach($output as &$item) {
    unset($item[2]);
}
unset($item); // unset reference
于 2011-08-31T16:46:00.793 回答
7

干净整洁:

$f = function(&$a,$k) { unset($a[1]); };
array_walk($arr, $f);

或者:

array_walk($arr, function (&$a, $k) {
  unset($a[1]); 
});
于 2011-08-31T16:53:06.387 回答
2

您将使用array_mapand的组合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)
  }
}
于 2011-08-31T16:48:24.717 回答
1
foreach($array as $key=>$val){ unset($val[1]); }
于 2011-08-31T16:47:43.750 回答
0

我用这个:

public function array_unset_key_in_children($array, $keyToUnsetInChildren)
{ 
    $newArray = [];
    foreach($array as $key=>$subArray) { 
        unset($subArray[$keyToUnsetInChild]);
        $newArray[$key] = $subArray;
    }
    return $newArray;
}
于 2021-04-11T18:35:46.260 回答