问题在于,当使用PHP7时,预期结果与PHP5不同,请参阅以下带有$ object2的示例。
我认为这三种方法是相同的,但似乎并非如此。
似乎在PHP7中,与$ object2一起使用的快捷方式返回变量的类型而不是值。
是否存在PHP7的某些环境配置,使其在此问题上的行为与PHP5类似?
$array1 = array();
$array1["Key"] = "Value";
$object1 = new stdClass();
$key1 = $array1["Key"];
$object1->Stream = new stdClass();
$object1->Stream->$key1 = 5;
echo json_encode($object1);
$array2 = array();
$array2["Key"] = "Value";
$object2 = new stdClass();
$object2->Stream = new stdClass();
$object2->Stream->$array2["Key"] = 5;
echo json_encode($object2);
$array3 = array();
$array3 = "Value";
$object3 = new stdClass();
$object3->Stream = new stdClass();
$object3->Stream->$array3 = 5;
echo json_encode($object3);
PHP5中的结果:
{"Stream":{"Value":5}}
{"Stream":{"Value":5}}
{"Stream":{"Value":5}}
PHP7中的结果:
{"Stream":{"Value":5}}
{"Stream":{"Array":{"Key":5}}}
{"Stream":{"Value":5}}
答案 0 :(得分:1)
尝试将其包装在{}
中$object2->Stream->{$array2["Key"]}
答案 1 :(得分:0)
您可以在变量中存储数组索引,然后在对象
中使用此变量尝试下面的代码
$array1 = array();
$array1["Key"] = "Value";
$object1 = new stdClass();
$key1 = $array1["Key"];
$object1->Stream = new stdClass();
$object1->Stream->$key1 = 5;
echo json_encode($object1);
$array2 = array();
$array2["Key"] = "Value";
$tmp = $array2["Key"];
$object2 = new stdClass();
$object2->Stream = new stdClass();
$object2->Stream->$tmp = 5;
echo json_encode($object2);
$array3 = array();
$array3 = "Value";
$object3 = new stdClass();
$object3->Stream = new stdClass();
$object3->Stream->$array3 = 5;
echo json_encode($object3);