PHP:从字符串获取SESSION变量

时间:2018-12-02 14:45:06

标签: php session-variables

我有这个$ res变量,它从数据库查询中获取结果。结果在字符串中包含会话变量的名称。该会话变量已经设置,并且值为5(INTIGER),例如:

$res = mysql_query('SELECT `result` from `table`....');
....
gives the $res variable this string value: "Result: $_SESSION[myVar]";
print_r($res); // outputs Result: $_SESSION[myVar] and not "Result: 5"

如何解析字符串以获取会话变量的值?

3 个答案:

答案 0 :(得分:1)

使用字符串串联:

$res = "Result: ".$_SESSION[myVar];
print_r($res);

答案 1 :(得分:0)

您需要启动会话并回显变量。

<?php
session_start();
$myvar=$_SESSION["myVar"];
echo "Result: ".$myvar;
?>

编辑:您可以做的是:

preg_match_all("/\[([^\]]*)\]/",$res,$matches);
$var=matches[1];
$session=$_SESSION[$var];
echo $session;

这将找到会话字符串中使用的var。然后将其输入到$ _SESSION中以获取该会话变量。

答案 2 :(得分:0)

应阅读 def get_nested_attributes(model, _attributes = []) # base case if model.nested_attributes_options.empty? nil # recurse deeper else associations_list = model.reflect_on_all_associations(:has_one) associations_list = associations_list.push(model.reflect_on_all_associations(:has_many)).flatten nested_attributes = associations_list.each_with_object({}) do |association , hash| association_model = association.klass.nil? ? association.name.to_s.classify.constantize : association.klass # include attributes of association model # { _attributes => [attributes_1, attribute_2] } attribute_name = :"#{association.name.to_s}_attributes" hash[attribute_name] = association_model .send(:attribute_names) .map(&:to_sym) # recurse deeper into tree, get the result and append # { _attributes => [attributes_1, attribute_2, { } ] } result = get_nested_attributes(association_model, hash[attribute_name]) if !result.nil? hash[attribute_name].push(result) end end nested_attributes end end model = Restaurant nested_attributes = get_nested_attributes(model) params.permit(nested_attributes)