遇到一个关于json的问题。有一组正则规则,由于有很多行(以后可能还需要增删)
所以在主页页面里用一个固定的foreach代码,然后将正则规则封装一个json数组,保存到外部文件(以后修改规则时只需修改这个外部文件)。json.txt代码
$json=<<<EOT
[{"a":"!preg_match('@www\\\.aaa\\\.com@',$url,$match)||!preg_match('@www\\\.bbb\\\.com@',$url,$match)||!preg_match('@www\\\.ccc\\\.com@',$url,$match)","b":"1"},{"a":"!preg_match('@www\\\.ddd\\\.com@',$url,$match)||!preg_match('@www\\\.eee\\\.com@',$url,$match)","b":"2"},{"a":"!preg_match('@www\\\.fff\\\.com@',$url,$match)||!preg_match('@www\\\.ggg\\\.com@',$url,$match)","b":"3"}]
EOT;php页面代码include("json.txt");
$date = json_decode($json);
foreach($date as $row){
if($row->a){
//做一些$row->b的事物
}
}但是现在$url,$match2个php变量在json_decode后消失了,试加花括号{$url},{$match2}也没用。
现在如何解决这个问题?不行的话不用json也可以。最终目前是封装成一个数值,可以用foreach循环读出。谢谢。jsonphp
所以在主页页面里用一个固定的foreach代码,然后将正则规则封装一个json数组,保存到外部文件(以后修改规则时只需修改这个外部文件)。json.txt代码
$json=<<<EOT
[{"a":"!preg_match('@www\\\.aaa\\\.com@',$url,$match)||!preg_match('@www\\\.bbb\\\.com@',$url,$match)||!preg_match('@www\\\.ccc\\\.com@',$url,$match)","b":"1"},{"a":"!preg_match('@www\\\.ddd\\\.com@',$url,$match)||!preg_match('@www\\\.eee\\\.com@',$url,$match)","b":"2"},{"a":"!preg_match('@www\\\.fff\\\.com@',$url,$match)||!preg_match('@www\\\.ggg\\\.com@',$url,$match)","b":"3"}]
EOT;php页面代码include("json.txt");
$date = json_decode($json);
foreach($date as $row){
if($row->a){
//做一些$row->b的事物
}
}但是现在$url,$match2个php变量在json_decode后消失了,试加花括号{$url},{$match2}也没用。
现在如何解决这个问题?不行的话不用json也可以。最终目前是封装成一个数值,可以用foreach循环读出。谢谢。jsonphp
....
EOT;
就不会使变量“消失”
但我不是道你对 '$var' 如何还原成变量
好像$var没作用了……一个很明显的正则等式,却不起作用。
还有什么方法吗?不一定要json,只要能达到效果。
[
{
"a": "!preg_match('@www\\.aaa\\.com@',$url,$match)&&!preg_match('@www\\.bbb\\.com@',$url,$match)&&!preg_match('@www\\.ccc\\.com@',$url,$match)",
"b": "1"
},
{
"a": "!preg_match('@www\\.ddd\\.com@',$url,$match)&&!preg_match('@www\\.eee\\.com@',$url,$match)",
"b": "2"
},
{
"a": "!preg_match('@www\\.fff\\.com@',$url,$match)",
"b": "3"
}
]
EOT;
$date = json_decode($json);
foreach($date as $row){
if(eval("return $row->a;")){
//echo $row->b.'<hr />';
}
}用eval()还原成变量。谢谢大家。