2016-09-06 3 views
1

を多次元連想配列を埋める:このような何かにビルドと私はこのような構造に変換する必要があり、多くの区切り文字列から

$source[0]["path"]; //"production.options.authentication.type" 
$source[0]["value"]; //"administrator" 
$source[1]["path"]; //"production.options.authentication.user" 
$source[1]["value"]; //"admin" 
$source[2]["path"]; //"production.options.authentication.password" 
$source[2]["value"]; //"1234" 
$source[3]["path"]; //"production.options.url" 
$source[3]["value"]; //"example.com" 
$source[4]["path"]; //"production.adapter" 
$source[4]["value"]; //"adap1" 

を:

$result["production"]["options"]["authentication"]["type"]; //"administrator" 
$result["production"]["options"]["authentication"]["user"]; //"admin" 
$result["production"]["options"]["authentication"]["password"]; //"1234" 
$result["production"]["options"]["url"]; //"example.com" 
$result["production"]["adapter"]; //"adap1" 

私は同様の質問を見つけましたが、私問題の私の特定のバージョンにそれを適応させることができません:PHP - Make multi-dimensional associative array from a delimited string

+1

これまでにどのようなコードを試しましたか? – gabe3886

+0

私はリンクされた質問の選択された回答に適応しようとしましたが、配列を1つの文字列から構築するだけで、構造体を置換せずに複数の文字列から配列を作成して値を入力することはできません。 – CarlosAS

+0

あなたが持っているコードを、それが動作していなくても投稿できますか?そうすれば、あなたが試したことを知ることができ、うまく機能していないものを見つけ出すことができます。 – gabe3886

答えて

1

あなたが苦しんでいた問題はよく分かりませんが、デモについては、https://eval.in/636072を参照してください。

$result = []; 

// Each item in $source represents a new value in the resulting array 
foreach ($source as $item) { 
    $keys = explode('.', $item['path']); 

    // Initialise current target to the top level of the array at each step 
    $target = &$result; 

    // Loop over each piece of the key, drilling deeper into the final array 
    foreach ($keys as $key) { 
     $target = &$target[$key]; 
    } 

    // When the keys are exhausted, assign the value to the target 
    $target = $item['value']; 
} 
+0

問題を完全に解決します。ありがとう! – CarlosAS

関連する問題