除了第一个元素外,是否可以删除数组中的所有空元素?看看这个例子:
Array (
[0] => val1
[1] => val2
[2] => val3
[3] =>
[4] => val4
[5] => val5
[6] => val6
[7] =>
[8] => val7
[9] => val8
[10] => val9
)
Array (
[0] => val1
[1] => val2
[2] => val3
[3] =>
[4] => val4
[5] => val5
[6] => val6
[7] => val7
[8] => val8
[9] => val9
)
这可能吗?哪种方法最好?
提前感谢您的帮助。
答案 0 :(得分:1)
简单的解决方案是:
$a = array(
'0' => 'val1',
'1' => 'val2',
'2' => 'val3',
'3' => '',
'4' => 'val4',
'5' => 'val5',
'6' => 'val6',
'7' => '',
'8' => 'val7',
'9' => 'val8',
'10' => 'val9',
);
// special flag to check if empty
// element already exists in new array
$has_empty = false;
$new_a = [];
foreach ($a as $el) {
if (!empty($el) || !$has_empty) {
$new_a[] = $el;
if (empty($el)) {
$has_empty = true;
}
}
}
echo'<pre>',print_r($new_a),'</pre>';
答案 1 :(得分:1)
您可以使用$first = false;
$result = array_filter($arr, function($k) use($first){
if(empty($k) && !first){
$first = true;
return true;
}
return !empty($k);
})
:
user$ pyvenv-3.x --without-pip my_venv_dir
user$ source my_venv_dir/bin/activate
user$ curl https://bootstrap.pypa.io/get-pip.py | python
user$ deactivate
user$ source my_venv_dir/bin/activat
(my_venv_dir) user$