2013-02-19 67 views
1

我試圖將導航位置字符串拆分爲主數組。php - 將字符串拆分爲多維數組

例如,如果我有這位置是1.2.2

我想將它添加主陣列中的如下

1 => 
    2 => 
     2 => array() 

然後,如果其他項目具有「2.1」的項目

1 => 
    2 => 
     2 => array() 
2 => 
    1 => array() 

然後另一 '1.2.3'

1 => 
    2 => 
     2 => array() 
     3 => array() 
2 => 
    1 => array() 

有沒有人知道這樣做的方法?

問候

編輯

可以說我有objectects的一個維數組,我想通過他們循環,並存儲爲結構化「導航」像嵌套數組。每個項目都有一個導航位置字符串,即1.2.3.6

我然後運行它通過某種陣列沃克放置對象在正確的位置思考$depth = explode('.', $details['navigation_pos']);

希望這有助於

編輯

也許是更好的方式把它是這樣的,但更優雅:

$depth = explode('.', '1.2.3.4'); 
$bar = json_decode('{"' . implode('":{"', $depth) . '":[]' . str_repeat('}', sizeof($depth))); 
print_r($bar); 

這將使

stdClass Object 
(
    [1] => stdClass Object 
     (
      [2] => stdClass Object 
       (
        [3] => stdClass Object 
         (
          [4] => Array 
           (
           ) 

         ) 

       ) 

     ) 

) 
+0

什麼是您的輸入是字符串還是數組,什麼應該是輸出? – 2013-02-19 07:02:12

+0

你的數組將被存儲在哪裏?在會議? – 2013-02-19 07:05:00

+0

@Luke Snowden,顯示您的確切字符串 – 2013-02-19 07:08:07

回答

0

你可以使用eval()但要小心:

eval()語言結構非常危險,因爲它允許執行任意PHP代碼。因此不鼓勵它的使用。如果您已經仔細覈實沒有其他選擇而不是使用此構造,請特別注意不要將任何用戶提供的數據傳遞給它,而不事先進行適當的驗證。

$final_array = array(); // The output array 

/* 
    Example: 
    $big_array = array(
     '1.1' => 'One-one', 
     '2.1.3.4' => 'Two-one-three-four' 
    ); 
*/ 

foreach ($big_array as $position_string => $item) 
{ 
    $index_array = explode(".", $position_string); 

    foreach ($index_array as $key => $value) 
    {  
     // Make sure only integers are put through eval() 
     $index_array[$key] = (int)$value; 
    } 

    $indexes = implode("][", $index_array); 

    // TODO: make sure $item is safe to put through eval()! 
    eval("\$final_array[{$indexes}] = \$item"); 
} 
+1

嗯,要測試以上。設法使它與以下工作 '$ depth = explode('。',$ details ['navigation_pos']); $ bar = json_decode('{「'。implode('」:{「',$ depth)。'」:{「name」:''。$ details ['name']。'「,」name「: 「'。$ details ['name']。'」}'。str_repeat('}',sizeof($ depth))); $ this-> navigation = array_merge_recursive($ this-> navigation,(array)$ bar);'以及 – 2013-02-19 08:01:26

+0

您也可以嘗試修改接受的答案來解決這個問題:http://stackoverflow.com/questions/2286706/php-lookup-array-contents-with-dot-syntax(所以它設置的值,而不是得到它) – Alasjo 2013-02-19 08:26:39

+0

好的解決方案盧克,我有同樣的情況。做得好,謝謝! – Karl 2014-01-23 00:34:17