gpt4 book ai didi

php - 从具有特定内容(特殊字符)的数组中删除元素

转载 作者:行者123 更新时间:2023-12-04 15:54:30 24 4
gpt4 key购买 nike

请求您帮助删除空数组元素,我尝试了 array_filterarray_map('array_filter', $array) 但似乎没有按预期工作。下面是数组结构和预期的输出,

原始数组

Array
(
[0] => [
[1] => [
[2] => [
[3] => "Test",
[4] => "Server1",
[5] => null,
[6] => "Server2",
[7] => null,
[8] => "",
[9] => "stopped",
[10] => ]
[11] => ]
[12] => ]
)

预期的数组输出

Array
(
[0] => "Test",
[1] => "Server1",
[2] => null,
[3] => "Server2",
[4] => null,
[5] => "",
[6] => "stopped",
)

请注意,不应删除 null"" 元素。

最佳答案

您可以使用 preg_match()检查 [] 上每个元素是否存在的函数:

preg_match ('/[\[\]]+/', $val, $matches);

如果有 - 跳过这个值。因此,如果您的输入数组具有如下结构:

$ar = Array
(
0 => "[",
1 => " [",
2 => " [",
3 => "Test",
4 => "Server1",
5 => null,
6 => "Server2",
7 => null,
8 => "",
9 => "stopped",
10 => " ]",
11 => " ]",
12 => "]",
);

此函数将删除相应的元素:

function cleanArray($ar){ 
$res = [];
foreach($ar as $val){
preg_match ('/[\[\]]+/', $val, $matches);
if(count($matches) == 0) $res[] = $val;
}
return $res;
}

Demo

关于php - 从具有特定内容(特殊字符)的数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59138706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com