Maison > Article > développement back-end > php foreach有关问题
php foreach问题,在线等
PC客户端POST如下json数据至后台,json result数组中的数据条目不固定,有时是1组,有时是3组,可能更多。
如:json result 数组中1组数据
{
"result" : [
{
"old_ip" : "61.141.251.21",
"new_ip" : "61.141.251.22",
"urldata" : "img1.taobao.com\r",
"normal" : "100",
"error" : "102",
"agent" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)\r"
}
]
}
如:json result 数组中3组数据
{
"result" : [
{
"old_ip" : "61.141.251.23",
"new_ip" : "61.141.251.24",
"urldata" : "img1.taobao.com\r",
"normal" : "100",
"error" : "102",
"agent" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)\r"
},
{
"old_ip" : "61.141.251.25",
"new_ip" : "61.141.251.26",
"urldata" : "img2.taobao.com\r",
"normal" : "100",
"error" : "102",
"agent" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)\r"
},
{
"old_ip" : "61.141.251.27",
"new_ip" : "61.141.251.28",
"urldata" : "img3.taobao.com\r",
"normal" : "100",
"error" : "102",
"agent" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)\r"
}
]
}
数据表:
CREATE TABLE `result` (
`id` int(10) unsigned NOT NULL auto_increment,
`old_ip` varchar(100) NOT NULL,
`new_ip` varchar(100) NOT NULL,
`urldata` varchar(100) NOT NULL,
`normal` varchar(10) NOT NULL,
`error` varchar(10) NOT NULL,
`agent` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
后台接收PHP代码:
$result=$_POST["result"];
$arr=json_decode($result,true);
?>
请教各位专家,如何使用foreach取出$arr中的数据,并写入数据库(需考虑result数据条目不固定的问题),格式如下,求完整代码!合适可加分!
id old_ip new_ip urldata normal error agent
1 61.141.251.21 61.141.251.22 img1.taobao.com 100 102 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)
2 61.141.251.23 61.141.251.24 img2.taobao.com 100 102 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)
------解决思路----------------------
<br />$user_ip=get_userip();<br /><br />$result=$_POST["result"]; <br /> <br />$arr=json_decode($result,true);<br />$arr=$arr['result'];<br /> <br />if($arr){<br /> foreach($arr as $val){<br /> $val['user_ip'] = $user_ip;<br /> $val = array_map('mysql_real_escape_string',$val);<br /> $str = "'".implode("','", $val)."'";<br /> $sqlstr = "insert into result(old_ip,new_ip,urldata,normal,error,agent,user_ip) values(".$str.")";<br /> echo $sqlstr.'<br>';<br /> mysql_query($sqlstr) or die(mysql_error());<br /> }<br />}<br />