坚持将此 javascipt 代码(从 SO)“转换”为 php。
考虑 "AAA='111' BBB='222' DD='333' CC='dao@toto.fr'"
来自先前 json 对象键的值。
1 - 从一些 API 帖子中收到此 json
{
"first_key": "first_value",
"sec_key": "sec_value",
"third_key": "AAA='111' BBB='222' DD='333' CC='dao@toto.fr'",
}
2 - 期望像这样将 Third_key 值导出为新的 json
{ "AAA": "111", "BBB": "222", "DD": "333", "CC": "dao@toto.fr" }
所以,
<body>
<script type="text/javascript">
var input="AAA='111' BBB='222' DD='333' CC='dao@toto.fr'";
var result={};
input.split("'").forEach(function(value,i,arr){
if(i%2===0) return;
var key=arr[i-1].trim().replace("=","");
result[key]=value;
});
console.log(result);
</script>
</body>
在控制台中得到这个,大约是我想要的:
Object { AAA: "111", BBB: "222", DD: "333", CC: "dao@toto.fr" }
预期输出:
Object { "AAA": "111", "BBB": "222", "DD": "333", "CC": "dao@toto.fr" }
如何在 PHP 中获得预期的输出?搜索引擎将我发送到与我要查找的内容无关的 json_encode/json_decode
函数。
最佳答案
在 PHP 中,您可以非常简单地使用正则表达式来提取名称和值,然后使用 array_combine()
将其结果组合到关联数组中,然后使用 json_encode( )
结果数组...
$third_key = "AAA='111' BBB='222' DD='333' CC='dao@toto.fr'";
preg_match_all("/(\w*)='(.*?)'/", $third_key, $matches);
print_r($matches);
echo json_encode(array_combine($matches[1], $matches[2]));
这给出了...
Array
(
[0] => Array
(
[0] => AAA='111'
[1] => BBB='222'
[2] => DD='333'
[3] => CC='dao@toto.fr'
)
[1] => Array
(
[0] => AAA
[1] => BBB
[2] => DD
[3] => CC
)
[2] => Array
(
[0] => 111
[1] => 222
[2] => 333
[3] => dao@toto.fr
)
)
{"AAA":"111","BBB":"222","DD":"333","CC":"dao@toto.fr"}
print_r($matches);
只是为了展示正则表达式如何将原始字符串拆分成它的部分,以及最后一行如何创建结束数组。
关于javascript - 从 json 键导出一些值作为新的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55678919/