Home  >  Article  >  Backend Development  >  请问一下PHP怎样在二维数组查找匹配字符串元素效率比较高

请问一下PHP怎样在二维数组查找匹配字符串元素效率比较高

WBOY
WBOYOriginal
2016-06-13 12:12:51966browse

请教一下PHP怎样在二维数组查找匹配字符串元素效率比较高
各位好!
不知道这样的标题对不对。
对算法不是很了解,想在一个二维数组中查找一个匹配的字符串元素。
数组的结构是这样的:

<br />array(<br />	2 => array(<br />		'catid' => 2,<br />		'catdir' => 'notice',<br />	)<br />	5 => array(<br />		'catid' => 5,<br />		'catdir' => 'subject',<br />	),<br />	6=> array(<br />		'catid' => 6,<br />		'catdir' => 'news'<br />	),<br />);<br />


是一个二维数组,第一维的下标是第二维的catid的值,顺序但不连续。现在有一个catdir的值,要在这个数组里查找出对应的catid。
刚开始有点二用二分查找,但发现貌似根本行不通。
请教下,有什么比遍历数组更有效的办法?

谢谢!


------解决思路----------------------
内置函数怎么着也比你用代码拼凑的效率高
就算你的表达有误,按查询键组织数据时,效率是最高的
因为哈希表的时间复杂度为 O(0),而一次遍历的时间复杂度为 O(n)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn