douzi2749 2017-04-13 05:25
浏览 27
已采纳

PHP数组为json格式

I am trying to create a chart based on some php data i got in an array, if I run the following

<?php     
    $out = array_values($periodi);  
    echo json_encode($out, JSON_PRETTY_PRINT); 
?>

I get this json format

   [
    "Francia",
    "Italia",
    "Italia",
    "Germania",
    "Afghanistan",
    "Italia"
]

While what I am looking for is to get a format like this. Regardless of different values how do I add a propriety name in roder to get something along those lines?

var data = [{
    "name": "Tokyo",
    "data": 3.0
}, {
    "name": "NewYork",
    "data": 2.0
}, {
    "name": "Berlin",
    "data": 3.5
}, {
    "name": "London",
    "data": 1.5
}];

print_r($periodi);

Array ( [0] => Moderno [1] => Contemporaneo [2] => Contemporaneo [3] => Contemporaneo [4] => Contemporaneo )

I have another array with different data but still the format is wrong:

Array ( [francese] => Array ( [maschio] => Array ( [0] => 1 ) [femmina] => Array ( [0] => 1 ) ) [chimica] => Array ( [maschio] => Array ( [0] => 1 [1] => 1 ) ) [fisica] => Array ( [maschio] => Array ( [0] => 1 [1] => 1 ) [femmina] => Array ( [0] => 1 ) ) [scienze] => Array ( [maschio] => Array ( [0] => 1 ) ) [inglese] => Array ( [maschio] => Array ( [0] => 1 ) ) [spagnolo] => Array ( [maschio] => Array ( [0] => 1 ) ) [italiano] => Array ( [femmina] => Array ( [0] => 1 ) ) )

 {
        "maschio": [
            true
        ],
        "femmina": [
            true
        ]
    },
    {
        "maschio": [
            true,
            true
        ]
    },
    {
        "maschio": [
            true,
            true
        ],
        "femmina": [
            true
        ]
    },
    {
        "maschio": [
            true
        ]
    },
    {
        "maschio": [
            true
        ]
    },
    {
        "maschio": [
            true
        ]
    },
    {
        "femmina": [
            true
        ]
    }
]
  • 写回答

3条回答 默认 最新

  • doufang8965 2017-04-13 05:36
    关注

    PHP code demo

    <?php
    $array=
        [
        "Moderno",
        "Contemporaneo",
        "Contemporaneo",
        "Contemporaneo",
        "Contemporaneo"
    ];
    
    $array=array_count_values($array);
    $result=array();
    foreach($array as $key => $value)
    {
        $result[]=array("name"=>$key,"data"=>$value);
    }
    print_r(json_encode($result));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB卫星二体模型仿真
  • ¥15 怎么让数码管亮的同时让led执行流水灯代码
  • ¥20 SAP HANA SQL Script 。如何判断字段值包含某个字符串
  • ¥85 cmd批处理参数如果含有双引号,该如何传入?
  • ¥15 fx2n系列plc的自控成型机模拟
  • ¥15 时间序列LSTM模型归回预测代码问题
  • ¥50 使用CUDA如何高效的做并行化处理,是否可以多个分段同时进行匹配计算处理?目前数据传输速度有些慢,如何提高速度,使用gdrcopy是否可行?请给出具体意见。
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),如何通过环岛的原理及完整代码
  • ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
  • ¥15 c语言数据结构高铁订票系统