[英]Remove lines with empty values from multidimensional-array in php
如何從PHP中刪除多維數組中具有空元素的行?
例如,來自:
1: a, b, c, d
2: d, _, b, a
3: a, b, _, _
4: d, c, b, a
5: _, b, c, d
6: d, c, b, a
至
1: a, b, c, d
4: d, c, b, a
6: d, c, b, a
謝謝!
$arr = array(... your multi dimension array here ...);
foreach($arr as $idx => $row) {
if (preg_grep('/^$/', $row)) {
unset($arr[$idx]);
}
}
使用此代碼:
$source = array(
array('a', 'b', 'c', 'd'),
array('d', '_', 'b', 'a'),
array('a', 'b', '_', '_'),
array('d', 'c', 'b', 'a'),
array('_', 'b', 'c', 'd'),
array('d', 'c', 'b', 'a'),
);
$sourceCount = count($source);
for($i=0; $i<$sourceCount; $i++)
{
if(in_array("_", $source[$i])) unset($source[$i]);
}
請參閱: http : //ideone.com/Vfd6Z
循環遍歷多維數組並檢查位置i
處的數組是否包含任何空元素。 如果是,請調用unset($arr[i])
將其刪除。
for($i=0,$size=sizeof($arr); $i < $size; $i++) {
if( in_array( "", $arr[$i] ) )
unset( $arr[$i] );
}
我會自己迭代一個foreach循環:
<?php
// Let's call our multidimensional array $md_array for this
foreach ($md_array as $key => $array)
{
$empty_flag = false;
foreach ($array as $key => $val)
{
if ($val == '')
{
$empty_flag = true;
}
}
if ($empty_flag == true)
{
unset($md_array[$key]);
}
}
?>
這幾乎肯定是一種更有效的方法,所以任何擁有更好解決方案的人都可以隨意讓我和Alex知道。
嘗試這個:
注意:$ arr是你的數組。
foreach ( $arr as $key => $line ) {
foreach ( $line as $item ) {
if ( empty( $item ) ) {
unset( $arr[$key] );
break;
}
}
}
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.