如何将PHP数组转换为指定结构的JSON输出并提取日期列表
PHP数组结构转换问题
现有输入数组
Array ( [0] => stdClass Object ( [Item1] => 10/12/2021 [Item2] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) ) [1] => stdClass Object ( [Item1] => 10/11/2021 [Item2] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) ) [2] => stdClass Object ( [Item1] => 10/10/2021 [Item2] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) ) [3] => stdClass Object ( [Item1] => 10/09/2021 [Item2] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) ) [4] => stdClass Object ( [Item1] => 10/08/2021 [Item2] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) ) [5] => stdClass Object ( [Item1] => 10/07/2021 [Item2] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) ) [6] => stdClass Object ( [Item1] => 10/06/2021 [Item2] => Array ( [0] => 3729195 [1] => 0 [2] => 0 [3] => 0 ) ) [7] => stdClass Object ( [Item1] => 10/05/2021 [Item2] => Array ( [0] => 7458390 [1] => 0 [2] => 0 [3] => 0 ) ) [8] => stdClass Object ( [Item1] => 10/04/2021 [Item2] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) ) [9] => stdClass Object ( [Item1] => 10/03/2021 [Item2] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) ) )
目标输出
目标JSON结构
[{name:"", data:[0,0,0,0,0,0,3729195,7458390,0,0]}, {name:"", data:[0,0,0,0,0,0,0,0,0,0]}, {name:"", data:[0,0,0,0,0,0,0,0,0,0]}, {name:"", data:[0,0,0,0,0,0,0,0,0,0]}]
目标日期列表
['10/12/2021', '10/11/2021', '10/10/2021', '10/09/2021', '10/08/2021', '10/07/2021', '10/06/2021', '10/05/2021', '10/04/2021', '10/03/2021']
错误原因
你之前的方案直接对原数组做JSON序列化后替换字段,本质是没有调整数据结构:原数组是按日期维度分组,每个元素对应1天的4个指标值,而需求是按Item2的下标维度分组,每个元素对应1个指标的10天数值,核心缺少行列转置的步骤。同时直接用字符串替换处理JSON容易出现误替换等边界问题,建议先调整数据结构再序列化。
正确实现代码
// 保留原有数据采集逻辑 $chartDataSeries = array(); $chartDateLabels = array(); foreach($jobs->charts_last10days as $chartData){ array_push($chartDateLabels, $chartData->Item1); array_push($chartDataSeries, $chartData->Item2); } // 输出日期列表,和需求格式完全匹配 $chartDateLabelsOutput = "['" . implode("', '", $chartDateLabels) . "']"; echo $chartDateLabelsOutput; // 初始化4个目标系列(对应Item2的4个下标) $targetSeries = []; for ($i = 0; $i < 4; $i++) { $targetSeries[] = [ 'name' => '', 'data' => [] ]; } // 行列转置填充数据 foreach ($chartDataSeries as $item2Arr) { foreach ($item2Arr as $index => $value) { $targetSeries[$index]['data'][] = $value; } } // 生成符合要求的JSON,如需严格标准JSON可删除下面的str_replace步骤 $targetJson = json_encode($targetSeries, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK); $targetJson = str_replace(['"name":','"data":'], ['name:','data:'], $targetJson); echo $targetJson;
内容的提问来源于stack exchange,提问作者Himesh Sharma
相关产品推荐
相关产品推荐

