取消多维数组中的数据
Unset data in a multidimensional array
我有 csv[ ][ ]。如何使用 for each 循环取消行中的数据设置?
for each ($index) {
if (conditions to meet) {
unset(csv[$index]);
}
}
试试这个:
foreach ($csv as $key => $value) {
unset($csv[$key]);
}
http://docs.php.net/manual/en/control-structures.foreach.php 说:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
这就是在使用两个 foreach 循环时修改行的单个元素时应该使用的方法。
<?php
$csv = [
[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7],
[4,5,6,7,8],
];
// make $row a reference
// so that unset($row[...]) affects $csv and not only a "copy".
foreach( $csv as &$row ) {
foreach( $row as $key=>$column ) {
if ( 0===$column%2 ) { // e.g. remove all even elements
unset( $row[$key] );
}
}
}
var_export($csv);
打印
array (
0 =>
array (
0 => 1,
2 => 3,
4 => 5,
),
1 =>
array (
1 => 3,
3 => 5,
),
2 =>
array (
0 => 3,
2 => 5,
4 => 7,
),
3 =>
array (
1 => 5,
3 => 7,
),
)
或者(相同的输出)没有 foreach 循环。
<?php
$csv = [
[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7],
[4,5,6,7,8],
];
$csv = array_map(
function($row) {
return array_filter(
$row,
function($col) {
return 0!==$col%2;
}
);
},
$csv
);
var_export($csv);
我有 csv[ ][ ]。如何使用 for each 循环取消行中的数据设置?
for each ($index) {
if (conditions to meet) {
unset(csv[$index]);
}
}
试试这个:
foreach ($csv as $key => $value) {
unset($csv[$key]);
}
http://docs.php.net/manual/en/control-structures.foreach.php 说:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
这就是在使用两个 foreach 循环时修改行的单个元素时应该使用的方法。
<?php
$csv = [
[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7],
[4,5,6,7,8],
];
// make $row a reference
// so that unset($row[...]) affects $csv and not only a "copy".
foreach( $csv as &$row ) {
foreach( $row as $key=>$column ) {
if ( 0===$column%2 ) { // e.g. remove all even elements
unset( $row[$key] );
}
}
}
var_export($csv);
打印
array (
0 =>
array (
0 => 1,
2 => 3,
4 => 5,
),
1 =>
array (
1 => 3,
3 => 5,
),
2 =>
array (
0 => 3,
2 => 5,
4 => 7,
),
3 =>
array (
1 => 5,
3 => 7,
),
)
或者(相同的输出)没有 foreach 循环。
<?php
$csv = [
[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7],
[4,5,6,7,8],
];
$csv = array_map(
function($row) {
return array_filter(
$row,
function($col) {
return 0!==$col%2;
}
);
},
$csv
);
var_export($csv);