你好,我在php中有一个数组,然后是一个输出
的json_encode函数{
"Machine": {
"cycle": 4230.7,
"percent": 73.26
},
"cycle": 6.63,
"percent": -0.45
}
我需要输出如下面的示例或者从json
中获取元素的替代方法这是理想的json格式和与之配合的代码
var text = '{"Machines":[' +
'{"cycle":"10","percent":"10" },' +
'{"cycle":"20","percent":"20" },' +
'{"cycle":"30","percent":"30" }]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.Machines[1].cycle+ " " + obj.Machines[1].percent;
以下是我在php中设置数组的方式
$Cycle = array(
"Machine" => array(
"cycle" => $machine1->Data(),
"percent" => $machine1->GetM()
),
"cycle" => $machine4->Data(),
"percent" => $machine4->GetM()
我想知道编写数组以适应示例json格式的最佳方法或更好的方法来获取json格式的循环和百分比值当前有感谢
答案 0 :(得分:0)
您不需要将JSON转换为文本,然后使用JSON.parse()将其读回来,只需使用JSON即可!
PHP:
<?php
$array = array(
'machine' => array(
array(
'cycle' => 12.34,
'percent' => 0.56,
),
array(
'cycle' => 56.78,
'percent' => 0.56,
),
)
);
print '<script>var foo = ' . json_encode($array) . '</script>';
JS:
console.log(foo.machine) // shows the array
console.log(foo.machine[1].cycle) // shows 56.87
答案 1 :(得分:0)
以下结构将为您提供正确的格式:
$Cycle = (object) array(
'Machines' => array(
(object) array(
'cycle' => $machine1->Data(),
'percent' => $machine1->GetM()
),
(object) array(
'cycle' => $machine2->Data(),
'percent' => $machine2->GetM()
),
)
);
答案 2 :(得分:-1)
<?php
$Cycle = array(
"Machines" => array(
array(
"cycle" => 'cycle1',
"percent" => '70.34'
), array(
"cycle" => 'cycle4',
"percent" => '20.34'
)
)
);
echo json_encode($Cycle);
将输出:
{"Machines":[{"cycle":"cycle1","percent":"70.34"},{"cycle":"cycle4","percent":"20.34"}]}
当它变得漂亮时:
{
"Machines": [{
"cycle": "cycle1",
"percent": "70.34"
}, {
"cycle": "cycle4",
"percent": "20.34"
}]
}