d3.js - PHP 数组格式

d3.js - PHP Array format

我需要使用 PHP 格式的数组为 JSON 创建一个 d3.js 图表。格式如下:

[
{
    "Category": "LV",
    "Percentage": 8 
},
{
    "Category": "CL",
    "Percentage": 20
},
{
    "Category": "Paed",
    "Percentage": 15
}
]

我目前拥有的数组代码和格式如下。

数组的格式显然需要更改,但我不确定如何更改以适应上述格式。

$data = array(
        array('LV' => round($low_vision_percentage, 2)), 
        array('CL' => round($contact_lenses_percentage, 2)), 
        array('Paed' => round($paediatrics_percentage, 2)),
        array('BV' => round($binocular_vision_percentage, 2)), 
        array('VT' => round($vision_therapy_percentage, 2)),  
        array('T' => round($therapeutics_percentage, 2)),
        array('R' => round($research_percentage, 2)), 
        array('CP' => round($clinical_practice_percentage, 2)),
        array('Op' => round($optics_percentage, 2)), 
        array('BVS' => round($broad_vision_sciences, 2)),
        array('Other' => round($other_percentage, 2)));

$json = json_encode($data);

$fp = fopen('categories.json', 'w');
fwrite($fp, $json);
fclose($fp);

最好的方法可能是从一开始就以所需的格式创建 $data 数组,因为这样效率更高,代码更少。见下文:

$data = [
    [
        "Category"=>"LV",
        "Percentage"=>round($low_vision_percentage, 2),
    ],
    [
        "Category"=>"CL",
        "Percentage"=>round($contact_lenses_percentage, 2),
    ],
    //... continue this pattern for other entries
];

但是,我不确定您是否像其他地方一样使用 $data。下面的代码将允许您使用 array_keys.

将当前的 data 转换为您想要的 d3jsFormattedData
$data = array(
        array('LV' => round($low_vision_percentage, 2)), 
        array('CL' => round($contact_lenses_percentage, 2)), 
        array('Paed' => round($paediatrics_percentage, 2)),
        array('BV' => round($binocular_vision_percentage, 2)), 
        array('VT' => round($vision_therapy_percentage, 2)),  
        array('T' => round($therapeutics_percentage, 2)),
        array('R' => round($research_percentage, 2)), 
        array('CP' => round($clinical_practice_percentage, 2)),
        array('Op' => round($optics_percentage, 2)), 
        array('BVS' => round($broad_vision_sciences, 2)),
        array('Other' => round($other_percentage, 2)));

$d3jsFormattedData = array_map(function($entry){
    //assume valid array entries are always available
    return [
        "Category"=>array_keys($entry)[0], //get first array key
        "Percentage"=>array_values($entry)[0] //get first array value
    ];
},$data);

//or safer approach

$d3jsFormattedData = array_filter(
    array_map(function($entry){
        //ensure non-empty arrays are available as elements
        if(!is_array($entry) || empty($entry)) return null; 
        $category = array_keys($entry)[0]; //still assuming 1 entry in each
        return [
            "Category"=> $category,
            "Percentage"=>$entry[$category]
        ];
    },$data), function($entry){
        return $entry != null; //remove invalid entries
});

注意。 [] 是 shorthand for array() ,你可以阅读更多 here on php arrays

让我知道这是否适合你。