分离JSON对象

时间:2018-04-17 08:17:34

标签: php jquery arrays json

我想将month_year与值分开,我该怎么做?

Screenshot of the output

  

样品输出:

  APR_2017   :   " 974144328"
  AUG_2017   :   " 1021696328"
  DEC_2017   :   " 1069248328"
  FEB_2017   :   " 950368328"
  JAN_2017   :   " 938480328"
  JAN_2018   :   " 1081136328"
  JUL_2017   :   " 1009808328"
  JUN_2017   :   " 997920328"
  MAR_2017   :   " 962256328"
  MAY_2017   :   " 986032328"
  NOV_2017   :   " 1057360328"
  OCT_2017   :   " 1045472328"
  SEP_2017   :   " 1033584328"

JQUERY CODE:

$.ajax({
    url: "overall-sales-chart.php",
    method: "POST",
    data: {activator:activator, data_show: data_show, start: start_date, end: end_date},
    dataType: "json",
    success: function(data){
        console.log(data);
    },
    error: function(data){
        console.log("error");
    }
});

PHP代码:

$start = new DateTime("2017-01-01");
$end = new DateTime("2018-01-01");

$smonth = (int)$start->format('Y')*12+(int)$start->format('n');
$emonth = (int)$end->format('Y')*12+(int)$end->format('n');

$firstmonth = min($smonth, $emonth);
$lastmonth = max($smonth, $emonth);
$months = array();

for ($i = $firstmonth; $i <= $lastmonth; $i++) {
    $thism = new DateTime(sprintf('%04d-%02d-01', intdiv($i, 12), $i % 12));
    $months[] = strtoupper($thism->format('M_Y'));
}

$m_total = implode(',', preg_replace('/^(.*)$/', 'SUM($1) AS $1', $months));

$sql = "SELECT $m_total FROM temp_sg_screen_sto_72_mos_summary";
$result = mysqli_query($conn, $sql);

$data = array();
foreach ($result as $row) {
    $data[] = $row;
} 

print json_encode($data);

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
var data={
'JAN_2017': "938480328",
'FEB_2017': "950368328",
'MAR_2017': "962256328", 
'APR_2017':"974144328",
'MAY_2017': "986032328"
};
$.each(data, function( index, value ) {
  console.log( index + ": " + value );
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
&#13;
&#13;
&#13;

这是一个代码片段。 而且,就你而言。

     success: function(data){
      $.each(data, function( index, value ) {
        console.log( index + ": " + value );
    });
}