从字符串创建密钥链
问题描述:
想,我有休耕JSON:从字符串创建密钥链
{
"foo.bar": 1
}
,我想挽救这个是这样的:
$array["foo"]["bar"] = 1
,但我也可以有超过2“参数“在字符串中。例如:
{
"foo.bar.another_foo.another_bar": 1
}
我想以同样的方式保存。
$array["foo"]["bar"]["another_foo"]["another_bar"] = 1
任何想法如果我不知道有多少个参数,我该怎么办?
答
这是远远不是最好的解决方案,但我一直在编程,所以我有点累,但我希望它给你一些工作,或至少一个工作的解决方案暂时。
下面是它的工作的IDEone:click
而这里的代码:
$json = '{
"foo.bar": 1
}';
$decoded = json_decode($json, true);
$data = array();
foreach ($decoded as $key => $value) {
$keys = explode('.', $key);
$data[] = buildNestedArray($keys, $value);
}
print_r($data);
function buildNestedArray($keys, $value) {
$new = array();
foreach ($keys as $key) {
if (empty($new)) {
$new[$key] = $value;
} else {
array_walk_recursive($new, function(&$item) use ($key, $value) {
if ($item === $value) {
$item = array($key => $value);
}
});
}
}
return $new;
}
输出:
Array
(
[0] => Array
(
[foo] => Array
(
[bar] => 1
)
)
)
不知道你的JSON字符串是否可能有数倍或不所以我让它处理了前者。
希望它有帮助,未来可能会回来并清理它。
答
开始用json_decode
然后建立一个foreach循环掰开密钥并将其传递到某种递归函数创建的值。
$old_stuff = json_decode($json_string);
$new_stuff = array();
foreach ($old_stuff AS $key => $value)
{
$parts = explode('.', $key);
create_parts($new_stuff, $parts, $value);
}
然后再编写递归函数:
function create_parts(&$new_stuff, $parts, $value)
{
$part = array_shift($parts);
if (!array_key_exists($part, $new_stuff)
{
$new_stuff[$part] = array();
}
if (!empty($parts)
{
create_parts($new_stuff[$part], $parts, $value);
}
else
{
$new_stuff = $value;
}
}
我没有测试此代码,所以不要指望只是削减和过去,但该战略应该工作。注意$ new_stuff是通过引用递归函数传递的。这个非常重要。
答
尝试下面的技巧为“重新格式化”到JSON字符串这将适合预期的阵列结构:
$json = '{
"foo.bar.another_foo.another_bar": 1
}';
$decoded = json_decode($json, TRUE);
$new_json = "{";
$key = key($decoded);
$keys = explode('.', $key);
$final_value = $decoded[$key];
$len = count($keys);
foreach ($keys as $k => $v) {
if ($k == 0) {
$new_json .= "\"$v\"";
} else {
$new_json .= ":{\"$v\"";
}
if ($k == $len - 1) $new_json .= ":$final_value";
}
$new_json .= str_repeat("}", $len);
var_dump($new_json); // '{"foo":{"bar":{"another_foo":{"another_bar":1}}}}'
$new_arr = json_decode($new_json, true);
var_dump($new_arr);
// the output:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
array (size=1)
'another_foo' =>
array (size=1)
'another_bar' => int 1