多次元配列を再帰的に作成する方法は?
-
06-07-2019 - |
質問
部分が文字列によって決定される多次元配列を作成しようとしています。区切り文字として。
を使用しています。各部分(最後を除く)は配列でなければなりません
例:
config.debug.router.strictMode = true
入力する場合と同じ結果が必要です:
$arr = array('config' => array('debug' => array('router' => array('strictMode' => true))));
この問題は本当に私を輪にさせてくれました。どんな助けでも大歓迎です。ありがとう!
解決
キーと値がすでに $ key
と $ val
にあると仮定して、これを行うことができます:
$key = 'config.debug.router.strictMode';
$val = true;
$path = explode('.', $key);
配列を左から右に埋める:
$arr = array();
$tmp = &$arr;
foreach ($path as $segment) {
$tmp[$segment] = array();
$tmp = &$tmp[$segment];
}
$tmp = $val;
そして右から左へ:
$arr = array();
$tmp = $val;
while ($segment = array_pop($path)) {
$tmp = array($segment => $tmp);
}
$arr = $tmp;
他のヒント
すべてを分割し、値から始めて、そこから逆方向に作業するたびに、別の配列の中にあるものをラップすると言います。そのように:
$s = 'config.debug.router.strictMode = true';
list($parts, $value) = explode(' = ', $s);
$parts = explode('.', $parts);
while($parts) {
$value = array(array_pop($parts) => $value);
}
print_r($parts);
エラーチェックができるように完全に書き換えます。
ガンボの答えは良さそうです。
ただし、典型的な.iniファイルを解析したいようです。
独自のコードをロールするのではなく、ライブラリコードを使用することを検討してください。
たとえば、 Zend_Config はこの種類を処理します物事のうまく。
これに対するJasonWolfの回答が本当に好きです。
起こりうるエラーについて:はい、しかし彼は素晴らしいアイデアを提供しました。今ではそれを防弾にするのは読者次第です。
私のニーズはもう少し基本的なものでした。区切りリストからMDアレイを作成します。私は彼のコードを少し修正して、それだけを提供しました。このバージョンでは、定義文字列の有無にかかわらず、または区切り文字なしの文字列でさえ配列を提供します。
誰かがこれをさらに改善できることを願っています。
$parts = "config.debug.router.strictMode";
$parts = explode(".", $parts);
$value = null;
while($parts) {
$value = array(array_pop($parts) => $value);
}
print_r($value);
// The attribute to the right of the equals sign
$rightOfEquals = true;
$leftOfEquals = "config.debug.router.strictMode";
// Array of identifiers
$identifiers = explode(".", $leftOfEquals);
// How many 'identifiers' we have
$numIdentifiers = count($identifiers);
// Iterate through each identifier backwards
// We do this backwards because we want the "innermost" array element
// to be defined first.
for ($i = ($numIdentifiers - 1); $i >=0; $i--)
{
// If we are looking at the "last" identifier, then we know what its
// value is. It is the thing directly to the right of the equals sign.
if ($i == ($numIdentifiers - 1))
{
$a = array($identifiers[$i] => $rightOfEquals);
}
// Otherwise, we recursively append our new attribute to the beginning of the array.
else
{
$a = array($identifiers[$i] => $a);
}
}
print_r($a);
所属していません StackOverflow