我需要帮助转换几个数组:
转换为单个JSON:
<?php
$message="";
$f="";
$mail_sent="";
if(isset($_POST['submit']))
{
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From:".$_POST['email']."\r\n";
$recipient="iam@myweb.com";
$subject = "CONTACT MAIL LETTER\n";
$message .= "<span style='font-family: verdana; font-size: 12px;'>Dear Sir, <br> "."<br> Contact Us details are displayed below <br><br>";
$message.='<tr><td><b><u>CONTACT US DETAILS</u></b></td><td></td><td></td></tr>';
$message.="<BR><BR><b>FIRST NAME:</b> ".$_POST['fname']. "<BR><BR>";
$message.="<BR><BR><b>LAST NAME:</b> ".$_POST['lname']. "<BR><BR>";
$message.="<b>E-MAIL ADDRESS:</b> ".$_POST['email']. "<BR><BR>";
$message.="<b>SUBJECT:</b> ".$_POST['subject']. "<BR><BR>";
$message.="<b>MESSAGE:</b> ".$_POST['message']. "<BR><BR><BR><BR><BR><BR><BR>";
$message .= "Thanks,<BR>".$_POST['fname']. "</span>";
//echo $message;
$mail_sent = @mail($recipient,$subject,$message,$headers);
if($mail_sent)
{
$f=1 ;
}
else
{
$f=0;
}
}
<?php
if(isset($_POST['submit']))
{
if($f==1)
{
echo "Your Mail has been sent Successfully.";
}
else
{
echo "Your Mail has not been sent Successfully.";
}
}
?>
这是否可以使用递归?我似乎无法让它正常工作,所以我想知道在JS中是否已经有一种简单的方法可以做到这一点。
答案 0 :(得分:3)
var struct = {};
var paths = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['d', 'g', 'h']
];
paths.forEach(function (path) {
var ref;
ref = struct;
path.forEach(function (elem, index) {
if (!ref[elem]) {
ref[elem] = index === path.length - 1 ? "done": {};
}
ref = ref[elem];
});
});
console.log(JSON.stringify(struct, null, "\t"));
输出:
{
"a": {
"b": {
"c": "done"
}
},
"d": {
"e": {
"f": "done"
},
"g": {
"h": "done"
}
}
}
注意:如果输入如下,则此脚本将失败:
var paths = [
['a', 'b', 'c'],
['a', 'b', 'c', 'd' ]
];
它决定c
应该是"done"
但是还有另一个级别。也许这不会发生,如果确实如此,找出你想要的结果。
答案 1 :(得分:0)
包含Array#forEach()
和Array#reduce()
var x = ['a', 'b', 'c'],
y = ['d', 'e', 'f'],
z = ['d', 'g', 'h'],
object = function (array) {
var o = {};
array.forEach(function (a) {
var last = a.pop();
a.reduce(function (r, b) {
r[b] = r[b] || {};
return r[b];
}, o)[last] = 'done';
});
return o;
}([x, y, z]);
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');