我正在尝试创建一个快速对象来处理我正在制作的图表。
输出如下:
[
['Firefox', 45.0],
['IE', 26.8],
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
我需要用来创建此数据的代码/循环:
$series = Array();
foreach($segmentData->segment as $segment){
echo $segment->segmentName . ' has ' . $segment->total . '<br />';
//Need to create the data here
}
最佳答案
由于提供的引用数组不是对象/非关联,因此您无法在 PHP 中创建键然后对其进行 json_encode。提供的引用数组只需要每个段有一个 2 元素数组。 只需使用 PHP 非关联数组创建数据即可。然后对数据进行 json_encode。这应该与您提供的引用数组完全匹配。
$output = array();
foreach($segmentData->segment as $segment){
array_push($output, array($segment->segmentName, $segment->total));
}
header("Content-type: application/json");
echo json_encode($output);
关于php - 使用 php 循环创建 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085202/