Php 数组搜索
Php 数组搜索,php,arrays,search,Php,Arrays,Search,$total是一个多维数组: Array ( [1] => Array ( [title] => Jake [date] => date ) [2] => Array ( [title] => John [date] => date ) [3] => Array ( [title] => Julia [date] => date ) ) 如何搜索[title]值并给出数组的结果ID 如果我们搜索Julia,它应该给出
$total
是一个多维数组:
Array (
[1] => Array ( [title] => Jake [date] => date )
[2] => Array ( [title] => John [date] => date )
[3] => Array ( [title] => Julia [date] => date )
)
如何搜索[title]
值并给出数组的结果ID
如果我们搜索Julia
,它应该给出3
(ID是[3]
)
谢谢。好的,很抱歉我之前的回答,没有注意到它是嵌套数组。您可以尝试以下方法:
function get_matching_key($needle, $innerkey, $haystack) {
foreach ($haystack as $key => $value ) {
if ($value[$innerkey] == $needle) {
return $key;
}
}
return NULL;
}
$key_you_want = get_matching_key("Julia", "title", $total);
function recursiveArraySearch($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
while($it->valid())
{
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
return $aIt->key();
}
$it->next();
}
return false;
}
$array = array(3 => array('title' => 'Julia'));
$key = recursiveArraySearch($array, 'Julia');
echo $key;
结果:
3
好的,很抱歉我之前的回答,没有注意到它是嵌套数组。您可以尝试以下方法:
function recursiveArraySearch($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
while($it->valid())
{
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
return $aIt->key();
}
$it->next();
}
return false;
}
$array = array(3 => array('title' => 'Julia'));
$key = recursiveArraySearch($array, 'Julia');
echo $key;
结果:
3
可能的解决方案:
function search_array($search,$array){
$cnt=count($array);
for($i=0;$i<$array;$i++){
if($search==$array[$i]['title']){
return $i;
}
}
}
函数搜索\u数组($search,$array){
$cnt=计数($array);
对于($i=0;$iposisible解决方案:
function search_array($search,$array){
$cnt=count($array);
for($i=0;$i<$array;$i++){
if($search==$array[$i]['title']){
return $i;
}
}
}
函数搜索\u数组($search,$array){
$cnt=计数($array);
对于($i=0;$i为$total
数组使用循环搜索。@Bang-Dao:每行?似乎太慢了。没有其他方法。多维数组上没有内置函数,所以必须为此类工作定义一个新函数为$total
数组使用循环搜索。@Bang-Dao:每行?似乎太慢了。没有其他方法。多维数组上没有内置函数,因此您必须为这种类型的工作数组_键($total)定义一个新函数?您是指数组_键($haystack)?为什么不简单:foreach($haystack as$key=>$value){if($value[$innerkey]=$needle){return key;}@马克-谢谢,我的PHP有点生锈-抱歉!编辑并制作了CW.array_-keys($total)?你是说array_-keys($haystack)?为什么不简单:foreach($haystack as$key=>$value){if($value[$innerkey]=$needle){return$key;}}@Mark谢谢,我的PHP有点生锈-抱歉!编辑并制作了CW。