2017-01-22 79 views
-1

我想弄清楚如何编写一个函数来完成两件事。如何检查多维数组中是否存在值并返回该数组

  1. 搜索多维数组的特定值(容易)
  2. 返回具有在其内的值的数组。

我一直在寻找所有的周末,我靠近了,但这件事是踢我的屁股。

这里是我的数组:

$keys = array(
'core' => array(
    'key'  => 'key1', 
    'directory' => "$core_dir/" 
), 
'plugins' => array(
    'key'  => 'key2', 
    'directory' => "$core_dir/plugins/" 
), 
'themes' => array(
    'key'  => 'key3', 
    'directory' => "$core_dir/$themes_dir/", 
    'theme'  => array(
     'theme1' => array(
      'key'  => 'theme_key1', 
      'directory' => "$core_dir/$themes_dir/theme1/" 
     ), 
     'theme2'  => array(
      'key'  => 'theme_key2', 
      'directory' => "$core_dir/$themes_dir/theme2/" 
     ) 
    ) 
), 

'hooks' => 'hook_key' 
); 

所以我要寻找的key1它将返回core阵列。 如果我搜索theme_key1它将返回theme1数组。

这里是我到目前为止的功能:(将它从阅读的分配和我在网上找到的另一个功能缝合在一起)。

function search_in_array($srchvalue, $array){ 
global $theme_key, $ext_key; 

if (is_array($array) && count($array) > 0){ 
    $foundkey = array_search($srchvalue, $array); 

    if ($foundkey === FALSE){ 

     foreach ($array as $key => $value){ 
      if (is_array($value) && count($value) > 0){ 
       $foundkey = search_in_array($srchvalue, $value); 


       if ($foundkey != FALSE){ 
        if(isset($_GET['th'])){ 

         $theme_array = $value; 

         return $theme_array; 
        }else{ 
         return $value; 
        } 

       } 
      } 
     } 
    } 
    else 
     return $foundkey; 
} 

}

+0

和问题是什么,没有功能的工作? – RomanPerekhrest

+0

它不会,它会返回'themes'数组,但我需要它下降一个级别,以便我可以获取'theme1'的数组。最终我会在数组中有不同的主题,所以如果我搜索'theme_key7',我需要能够获得'theme7'的数组。如果这是有道理的:/ – GeneralCan

回答

1
  1. 搜索多维数组的特定值(容易)返回

  2. 具有在其内的值的数组。

简短的解决方案使用RecursiveIteratorIteratorRecursiveArrayIteratoriterator_to_array功能:

$search_value = 'theme_key2'; 
$it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($keys)); 
$arr = []; 
foreach ($it as $v) { 
    if ($v == $search_value) { 
     $arr = iterator_to_array($it->getInnerIterator()); 
     break; 
    } 
} 

print_r($arr); 

输出将是:

Array 
(
    [key] => theme_key2 
    [directory] => <your custom variable values here -> $core_dir/$themes_dir>/theme2/ 
) 
+0

哇,这是超级有趣。我从来没有听说过'RecursiveIteratorIterator'和'RecursiveArrayIterator'。要看那些 – GeneralCan

+0

@GeneralCan,是的,有时他们可以非常有用 – RomanPerekhrest

1

不要复杂太多。您可以使用递归函数深入嵌套数组。

function return_array($arr, $value) { 
    $arr_found = array(); 
    foreach($arr as $key => $arr_value) { 
     if(is_array($arr_value)) { 
      if(in_array($value, $arr_value)) { 
       return array($key => $arr_value); 
      } 
      $arr_found = return_array($arr_value, $value); 
     } else { 
      if($arr_value == $value) { 
       $arr_found = array($key => $arr_value); 
      } 
     } 
    } 

    return $arr_found; 
} 

echo "<p>" . var_dump(return_array($keys, 'key1')) . "</p>"; 
echo "<p>" . var_dump(return_array($keys, 'theme_key1')) . "</p>"; 

希望它有帮助!

+0

DUUUUDEEEE !!真棒,非常感谢你。学到了新东西! – GeneralCan

+0

是的。很高兴你学到了新东西。别客气。 :) – Perumal

相关问题