1
我有csv [] []。我如何使用每個循環來取消行中的數據?取消多維數組中的數據
for each ($index) {
if (conditions to meet) {
unset(csv[$index]);
}
}
我有csv [] []。我如何使用每個循環來取消行中的數據?取消多維數組中的數據
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說:
爲了能夠直接修改環路普瑞森$值中數組元素與&。在這種情況下,價值將由 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);
的foreach($ CSV爲$密鑰=> $值){ 如果(0 === strpos($ CSV [$鍵] [0], '壞的')){ 未設置($ CSV [ $關鍵]); } }謝謝:) – Dio