这是数组,我只需删除数组的最后一个空值,如rtrim 。
[0] => Array
(
[0] => 6
[1] => 50967
[2] => 50647
[3] => 4024
[4] =>
[5] => testme
[6] => 125
[7] => onlinecode.org
[8] =>
[9] => You
[10] => 4
[11] => Toys
[12] => 135
[13] =>
[14] =>
[15] =>
)
我正在使用此代码:
print_r(array_filter($arr, 'strlen'));
但它删除了数组的所有空值。
预期产出:
[0] => Array
(
[0] => 6
[1] => 50967
[2] => 50647
[3] => 4024
[4] =>
[5] => testme
[6] => 125
[7] => onlinecode.org
[8] =>
[9] => You
[10] => 4
[11] => Toys
[12] => 135
)
答案 0 :(得分:1)
假设$ arr是二维数组(在OP中没有清楚地显示),如果为空,这将删除每个子数组的最后一个成员:
foreach ($arr as $key => $val) {
if (trim($val[count($val) - 1]) == '') {
unset($val[count($val) - 1]);
}
}
答案 1 :(得分:0)
以下代码将执行您想要的操作:
<?php
$a = 1;
$b = 2;
$c = 3;
$d = 4;
$arr = array(
array ( $b, $d, $c, $a, $b),
array ($c, $a),
array ( $b, $d, $c ),
array( $c, $d, $a, $b, $b)
);
echo "before:\n";
print_r($arr);
foreach($arr as $k1=>$q) {
foreach($q as $k2=>$r) {
if($r == $c) {
unset($arr[$k1][$k2]);
}
}
}
echo "after:\n";
print_r($arr);
?>
输出:
before:
Array
(
[0] => Array
(
[0] => 2
[1] => 4
[2] => 3
[3] => 1
[4] => 2
)
[1] => Array
(
[0] => 3
[1] => 1
)
[2] => Array
(
[0] => 2
[1] => 4
[2] => 3
)
[3] => Array
(
[0] => 3
[1] => 4
[2] => 1
[3] => 2
[4] => 2
)
)
after:
Array
(
[0] => Array
(
[0] => 2
[1] => 4
[3] => 1
[4] => 2
)
[1] => Array
(
[1] => 1
)
[2] => Array
(
[0] => 2
[1] => 4
)
[3] => Array
(
[1] => 4
[2] => 1
[3] => 2
[4] => 2
)
)
正如你所看到的,所有3个已经消失了......
答案 2 :(得分:0)
您可以测试最后一个数组项,如果它是空的,请将其删除。
修改增加了对OP $arr
$found_value = 0;
foreach ($arr as &$array) {
do {
if (empty(($array[count($array)-1]))) {
array_pop($array);
} else {
$found_value = 1;
}
} while (empty($found_value));
}
答案 3 :(得分:0)
您可以使用PHP array_reverse
来解决您的问题。
你可以这样做:
// Let Array be
$arr = [1, 2, 3, 4, null, 6, null, null];
foreach (array_reverse($arr) as $value) {
if(is_null($value)) {
unset($arr[count($arr) - 1]);
} else {
break;
}
}
print_r($arr);
/* Output
array:7 [
0 => 1
1 => 2
2 => 3
3 => 4
4 => null
5 => 6
] */
希望这有帮助!
答案 4 :(得分:0)
使用分隔符将Array转换为字符串。然后修剪最后的分隔线。终于转回来了。
<?php
$multiArray = [
[1,2,3,4,null,6,null,null],
[2,3,4,5,null, 8, null, 8, null, null]
];
var_dump(array_map("mytrim", $multiArray));
function mytrim($array)
{
return explode(',', rtrim( implode(',', $array), ','));
}
然后输出:
kris-roofe@krisroofe-Rev-station:~$ php cal.php
array(2) {
[0]=>
array(6) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
[3]=>
string(1) "4"
[4]=>
string(0) ""
[5]=>
string(1) "6"
}
[1]=>
array(8) {
[0]=>
string(1) "2"
[1]=>
string(1) "3"
[2]=>
string(1) "4"
[3]=>
string(1) "5"
[4]=>
string(0) ""
[5]=>
string(1) "8"
[6]=>
string(0) ""
[7]=>
string(1) "8"
}
}