[英]Best way to use a variable from Json_encode
I am creating a bit of code to take variables from php and show them with JavaScript i have used Json 我正在创建一些代码来从php中获取变量并使用JavaScript显示它们,我已经使用了Json
{"ZW01001":[{"cycle":4051.23,"Percent":73.26}]}
what is the best way to then get the Cycle from the Json in to the cycle variable of the If statement also the Json_encoede result will have 14 arrays total so for example 什么是最好的方法,然后将循环从Json插入到If语句的循环变量,而且Json_encoede结果总共将有14个数组,因此例如
{"ZW01004":[{"cycle":SomeValue,"Percent":SomeValue}]}
{"ZW01005":[{"cycle":SomeValue,"Percent":SomeValue}]}
and the part of the If statement for choosing the the element by Id should correspond to the ZW number at the start of each array 并且If语句中用于通过ID选择元素的部分应与每个数组开头的ZW号相对应
function Machinecycle(){
var machines = <?PHP echo json_encode($Cycle); ?>
if (cycle in machines < 480) {
document.getElementById("ZL01001").style.backgroundColor = 'lime';
document.write(Cycle);
} else {
document.getElementById("ZL01001").style.backgroundColor = 'red';
}
}
}
This is the output of Json_encode 这是Json_encode的输出
{"ZW01001":{"0":{"cycle":4095.12,"percent":73.258823529412},"ZW01004":[{"cycle":5.95,"percent":-0.41661805150429}]}}
This is the output of var_dump($Cycle); 这是var_dump($ Cycle);的输出;
array(1) { ["ZW01001"]=> array(2) { [0]=> array(2) { ["cycle"]=> float(4097.15) ["percent"]=> float(73.258823529412) } ["ZW01004"]=> array(1) { [0]=> array(2) { ["cycle"]=> float(7.98) ["percent"]=> float(-0.41661805150429) } } } }
This is the Php code, i have shortened it down to just 2 for ease use 这是Php代码,为了方便使用,我将其缩短为2
$Cycle = array(
"ZW01001" => array(
array(
"cycle" => $machine1->Data(),
"percent" => $machine1->GetM()
),
"ZW01004" => array(
array(
"cycle" => $machine4->Data(),
"percent" => $machine4->GetM()
),
If you want to know if any of the elements have cycle
less than 480
, you need to write a loop. 如果您想知道任何元素的
cycle
小于480
,则需要编写一个循环。
function Machinecycle(){
var machines = <?PHP echo json_encode($Cycle); ?>
for (var key in machines) {
if (machines[key].cycle < 480) {
document.getElementById(key).style.backgroundColor = 'lime';
document.write(Cycle);
} else {
document.getElementById(key).style.backgroundColor = 'red';
}
}
}
It also seems wrong to mix DOM functions and document.write()
. 混合DOM函数和
document.write()
似乎也是错误的。 What is the latter for? 后者是干什么的?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.