我有一个这样的数组:
Array
(
[0] => Array
(
[0] => 1
[1] => Firstname one
[2] => Lastname one
)
[1] => Array
(
[0] => 2
[1] => Firstname two
[2] => Lastname two
)
[2] => Array
(
[0] => 3
[1] => Firstname three
[2] => Lastname three
)
)
现在,我想删除整个index 1
,即数组中的所有名字。我计划通过遍历整个数组并删除它的索引来使用array_splice
。但是有更好的方法。 (我希望在删除元素后重新编制索引。)
答案 0 :(得分:1)
$yourarray = array_map(function($el) {
unset($el[1]); //remove index 1
return array_values($el); //return and reindex
}, $yourarray);
答案 1 :(得分:1)
您还可以使用array_slice
功能
foreach($array as $k=>$v)
{
array_splice($v, 1,1);
$array[$k] = $v;
}
输出:
Array
(
[0] => Array
(
[0] => 1
[1] => Lastname one
)
[1] => Array
(
[0] => 1
[1] => Lastname two
)
[2] => Array
(
[0] => 1
[1] => Lastname three
)
)
答案 2 :(得分:1)
您应该使用array_map
$input_array = [[1,'Firstname one','Lastname one'],
[2,'Firstname two','Lastname two'],
[3,'Firstname three','Lastname three']];
$resultArray = array_map(function($record) {
return [$record[0], $record[2]]; // add your desired records
}, $input_array);
echo '<pre>'; print_r($resultArray);
<强>输出强>: -
Array
(
[0] => Array
(
[0] => 1
[1] => Lastname one
)
[1] => Array
(
[0] => 2
[1] => Lastname two
)
[2] => Array
(
[0] => 3
[1] => Lastname three
)
)
答案 3 :(得分:-1)
foreach($array as $k=>$v)
{
unset($array[$k][1]); /// Chnage the key of array which you want to remove
}