2016-09-21 82 views
0

我有这样的事情来自我的SQL查询。我存储的变量名希望我可以传递在PHP中的变量值,但它不认识的价值观。如何使用存储在php中的SQL表中的变量名称

[{"dataField":"711","caption":"Product Gas Type","max_length":2,"min_length":0,"validationRules":[{"type":"pattern","pattern":"^[a-zA-Z0-9.]{'.$minVal.','.$maxVal.'}$","message":"This field only accepts letters and numbers. The lentgh has to be between '. $minVal .' and '. $maxVal .'"}]},{"dataField":"712","caption":"1St Charge Charging Point","max_length":2,"min_length":0,"validationRules":[{"type":"pattern","pattern":"^[a-zA-Z0-9.]{'.$minVal.','.$maxVal.'}$","message":"This field only accepts letters and numbers. The lentgh has to be between '. $minVal .' and '. $maxVal .'"}]}] 

我想说:

$minVal=1; 
    $maxVal=4; 

但我$结果变量从未识别变量(最小和最大丘壑)值。我该如何做这样的事情?我的理想最终的结果是这样的:

[{"dataField":"711","caption":"Product Gas Type","max_length":2,"min_length":0,"validationRules":[{"type":"pattern","pattern":"^[a-zA-Z0-9.]{1,4}$","message":"This field only accepts letters and numbers. The lentgh has to be between 1 and 4"}]},{"dataField":"712","caption":"1St Charge Charging Point","max_length":2,"min_length":0,"validationRules":[{"type":"pattern","pattern":"^[a-zA-Z0-9.]{1,4}$","message":"This field only accepts letters and numbers. The lentgh has to be between 1 and 4"}]}] 

我曾尝试做如下:

print_r(str_replace('$minVal', $minVal,$result[$i]->validationRules[0]->pattern)); 

此打印正确的事情,但它不会改变我原来的变量($结果),也当我尝试添加同为$ MAXVAL它取代$ MINVAL字$ MAXVAL

我使用pre_replace也试过,但甚至不会打印出任何东西

我想问题可能是这个变量名在$ result结果中,里面的结果是validationRules数组,因此可能这就是为什么字符串替换不能访问它们并更改整个原始数组

任何帮助将不胜感激!

+1

您将不得不使用'eval()',但这会变得非常成问题。我建议你看看使用模板库。 – Barmar

+1

'str_replace()'方法应该可以工作。但是你不应该在SQL数据中有'.'连接操作符。 SQL数据不会作为PHP代码执行,因此您不应该有运算符,引号等。 – Barmar

+0

您可以使用sprintf([示例](https://eval.in/private/36948631fa0114)),但当存在多个重复的变量,你将开始必须实现或使用模板引擎。 –

回答

0

原始输出只是纯文本,不会将变量识别为子字符串。你可以尝试一些丑陋这样的(和它的工作):

$raw_output = '{"dataField":"711","caption":"Product Gas Type","max_length":2,"min_length":0,"validationRules":[{"type":"pattern","pattern":"^[a-zA-Z0-9.]{'.$minVal.','.$maxVal.'}$","message":"This field only accepts letters and numbers. The lentgh has to be between '. $minVal .' and '. $maxVal .'"}]},{"dataField":"712","caption":"1St Charge Charging Point","max_length":2,"min_length":0,"validationRules":[{"type":"pattern","pattern":"^[a-zA-Z0-9.]{'.$minVal.','.$maxVal.'}$","message":"This field only accepts letters and numbers. The lentgh has to be between '. $minVal .' and '. $maxVal .'"}]}'; 

在$ MINVAL字符串然后爆炸:

$explode = explode("' . $minVal . '", $raw_output); 
$count = count($explode); 
$count_minus_one = $count - 1; 
$processed_output = ''; 
for($i = 0; $i < $count_minus_one; $i++) { 
    $processed_output .= $explode[$i] . $minVal; 
} 
$processed_output .= $explode[$count_minus_one]; 

然后重复$ MAXVAL。

相关问题