如何过滤 sql 数组的索引并显示它们..?



我有一个名为 dsr 的状态报告数据库表

它有一些索引命名为 nlanestatus1, nlanestatus2 ...依此类推,slanestatus1,slanestatus2 ...等等..

我一直在尝试通过以下方式过滤这些值

$array = array_filter($dsr, function($key) {
return strpos($key, 'lanestatus') === 0;
}, ARRAY_FILTER_USE_KEY);

我从堆栈溢出的另一个问题中获取了这段代码,并了解到通过在 function($key( 中将 0 的值更改为 1,我可以获得所需的键,但是在尝试了这段代码之后,我发现这个函数不起作用。 我尝试将 3 等于更改为 2 等于,它只显示整个$dsr数组。php编码中的任何帮助都会有所帮助。

解决它的另一种方法是更改 mysql 索引,但系统已经在工作,更改它们可能会破坏它,因此它不是一种选择。

strpos 查找字符串中键的位置。在这种情况下,它在 f.e. 'nlanestatus2' 中搜索 'lanestates',这个位置永远不会是 0,因为 0 将是第一个位置。

如果你想使用 strpos,这将解决

return strpos($key, 'lanestatus');

但实际上你不需要$key的位置,所以我建议使用 strstr

return strstr($key, 'lanestatus');

将函数修改为:

$array = array_filter($dsr, function($key) {
return strpos($key, 'lanestatus') !== false;
}, ARRAY_FILTER_USE_KEY);

在您的情况下

strpos($key, 'lanestatus') === 0;

表示您检查密钥是否以lanestatus开头。但是,由于您的密钥nlanestatus1slanestatus1因此它们永远不会以lanestatus开头。

如果您 100% 确定lanestatus前面是一个符号,您可以使用:

$array = array_filter($dsr, function($key) {
// check that position of `lanestatus` starts from position 1 in `$key`
return strpos($key, 'lanestatus') === 1;
}, ARRAY_FILTER_USE_KEY);

怎么样:

$array = [];
foreach($dsr as $index) {
if(strpos($index, 'lanestatus') !== false) {
$array[] = $index;
}
}

最新更新