简体   繁体   中英

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

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

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

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

{"ZW01001":{"0":{"cycle":4095.12,"percent":73.258823529412},"ZW01004":[{"cycle":5.95,"percent":-0.41661805150429}]}}

This is the output of 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

$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.

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() . What is the latter for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM