2017-01-22 163 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