如何使用存储在php

时间:2016-09-21 21:10:07

标签: php sql arrays preg-replace str-replace

我有类似的东西来自我的SQL查询。我存储变量名称希望我可以在php中传递变量值,但它不能识别值。

[{"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;

但我的$ result变量从不识别变量(最小和最大值)值。我怎么能这样做?我理想的最终结果是这样的:

   [{"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));

这打印正确的东西,但它不会改变我的原始变量($ result),当我尝试为$ maxVal添加相同的东西时,它会用$ maxVal

替换$ minVal

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

我认为问题可能是这个变量名称在$ result内部,而在inside结果中有validationRules数组,所以也许这就是为什么字符串替换无法访问它们并更改整个原始数组

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分: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。