在PHP中搜索多维数组并返回键
我面临以下问题:我建立了一个代表图标库"的网站.它基本上显示包含图标附加属性的 CSV 文件的内容,例如
I'm facing following issue: I've set up a website representing an "Icon Library". It basically shows the contents of a CSV file containing additional attributes for an icon, e.g.
- 文件名
- 工具提示
- 标签
- 状态(完成,进行中)
- 文件类型
- png
- 在目录中找到的文件名
- 在目录中找到的文件名
- 在目录中找到的文件名
最后所有东西都放在一个大数组中:
In the end everything is put into a big array:
[390] => Array ( [0] => hammer [1] => Properties [2] => tools, hammer, properties [3] => [4] => done [png] => Array ( [0] => hammer_16x.png [1] => hammer_32x.png ) [eps] => Array ( [0] => hammer_16x.eps [1] => hammer_32x.eps ) [ico] => Array ( [0] => hammer.ico ) )
现在我想提供在这个数组中搜索的可能性,并根据搜索结果过滤网站上显示的内容.因此,我想至少搜索以下字符串:
Now I would like to provide the possibility to search in this array and filter the contents displayed on the website based on the search result. Therefore I would like to search at least for following strings:
[0] => hammer [1] => Properties [2] => tools, hammer, properties [3] => [4] => done
任何提示我如何做到这一点?非常感谢!
Any hints how I could do that? Thanks a lot!
- png
您可以将 array_filter
与 array_diff_assoc
结合使用.有点像这样:
You may use array_filter
in conjunction with array_diff_assoc
.
Somehow like this:
function filter($array, $filter_elem) {
return array_filter($array, function ($v) use($filter_elem) {
return count(array_diff_assoc($filter_elem, $v)) == 0;
});
}
$array = array(
'390' => array(
'0' => 'hammer',
'1' => 'Properties',
'2' => 'tools, hammer, properties',
'3' => false,
'4' => 'done',
'png' => array(
'0' => 'hammer_16x.png',
'1' => 'hammer_32x.png',
),
'eps' => array(
'0' => 'hammer_16x.eps',
'1' => 'hammer_32x.eps',
),
'ico' => array(
'0' => 'hammer.ico',
),
),
...
);
$filter_elem = array(
'1' => 'Properties',
'2' => 'tools, hammer, properties',
'3' => false,
'4' => 'done',
);
print_r(filter($array, $filter_elem));