2012-05-09 36 views
2

我創建從PHP數組JSON編碼的數據,可以是兩個或三個級別深度,即看起來像這樣:拆分字符串以形成多維數組鍵?

[grandParent] => Array (
         [parent] => Array (
             [child] => myValue 
            ) 
        ) 

的方法我有,這是簡單地在手動創建嵌套數組代碼需要我鍵入了一些可怕的嵌套數組來用我的「的SetOption」功能(該功能後處理的編碼),但是:

$option = setOption("grandParent",array("parent"=>array("child"=>"myValue"))); 

我希望能夠通過使用類似的符號來javascript來得到相同的結果在這種情況下,因爲我將在許多頁面中設置很多選項,而上面的內容並不是很詳細能,尤其是當嵌套數組包含多個鍵 - 而能夠做到這將使更多的意義:

$option = setOption("grandParent.parent.child","myValue"); 

任何人都可以提出一個方法能夠通過對分割字符串創建多維數組「 「。這樣我可以json_encode()它成爲一個嵌套的對象?

(中的SetOption功能的目的都是一氣呵成以後的編碼之前,收集所有的選項連成一個大的,嵌套的PHP數組,因此,這就是解決方案會去)

編輯:我知道我可以在代碼中做到這一點:

$options['grandparent']['parent']['child'] = "myValue1"; 
$options['grandparent']['parent']['child2'] = "myValue2"; 
$options['grandparent']['parent']['child3'] = "myValue3"; 

這可能更簡單;但建議將仍然岩石(如我使用它作爲一個更廣泛的目標的一部分,所以它$obj->setOption(key,value);

+0

有人剛剛問同樣的問題。讓我們看看我能否找到它。 –

+0

[找到它](http:// stackoverflow。com/questions/10424335/php-convert-multidimensional-array-to-2d-array-with-dot-notation-keys) –

+0

我認爲這就是我正在尋找的對立面:(我想從點開始作爲一個字符串的符號,並轉換成一個PHP多維數組。 – Codecraft

回答

8

這應該,如果他們還沒有被創建並設置相應的鍵(codepad here)來填充子陣爲您提供:

function set_opt(&$array_ptr, $key, $value) { 

    $keys = explode('.', $key); 

    // extract the last key 
    $last_key = array_pop($keys); 

    // walk/build the array to the specified key 
    while ($arr_key = array_shift($keys)) { 
    if (!array_key_exists($arr_key, $array_ptr)) { 
     $array_ptr[$arr_key] = array(); 
    } 
    $array_ptr = &$array_ptr[$arr_key]; 
    } 

    // set the final key 
    $array_ptr[$last_key] = $value; 
} 

說它像這樣:

$opt_array = array(); 
$key = 'grandParent.parent.child'; 

set_opt($opt_array, $key, 'foobar'); 

print_r($opt_array); 

在了您的修改保持一致,你可能會想適應這個使用你的類內的array ...但希望這提供了一個開始的地方!

+0

結果在一堆錯誤和警告'呼叫時傳遞引用已被棄用'以及未定義的變量和錯誤的參數,但似乎產生什麼需要在最後...目前這是最接近的解決方案。 – Codecraft

+0

我將該參考從函數定義移至調用中...請隨時在其中運行時提出其他錯誤/修復建議! – rjz

+0

它需要是函數set_opt(&array_ptr,...並且在沒有&的情況下調用它,以消除錯誤! – Codecraft

0

什麼$option = setOption("grandParent", { parent:{ child:"myValue" } });

$options['grandparent']['parent']['child']如果$options['grandparent']['parent']不前設置會產生錯誤。

+0

我很擔心代碼的可讀性(和易於打字/編輯它),這將是不容易當有很多子鍵嵌套到數組中時,並且,當所有對setOption的調用都完成時,它應該建立一個PHP數組,然後通過json_encode()傳遞一次 - 所以你在那裏看不到就像它會工作 – Codecraft

0

接受的答案(http://codepad.org/t7KdNMwV)

​​
0

@rjz解決方案幫了我,儘管我需要創建一套密鑰存儲在陣列中的陣列的OO版本但是當涉及到數字指標時,它並不奏效。對於那些誰需要在陣列創建一套數組索引存儲的嵌套數組如下:

$keys = array(
    'variable_data', 
    '0', 
    'var_type' 
); 

你會發現這裏的解決方案:Php array from set of keys