php标准json格式化,使用PHP格式化JSON

我需要一些帮助正确格式化我的

JSON.为每个活动创建父对象,然后将子对象添加到它们.使用下面的示例数据,它将是具有两个孩子的’Test’的一个父活动,以及具有三个孩子的’Test2’的另一个父活动.我用两种jsonblobs链接了我正在获取的格式和我需要的格式.任何帮助,将不胜感激.

+---------------+-------+--------------+------------+------------+--------+

| ACTIVITY_NAME | GROUP | START_DATE | END_DATE | COMPLETED | TOTAL |

+---------------+-------+--------------+------------+------------+--------+

| Test | 1 | 04/30/2015 | 05/01/2015| 10 | 15 |

| Test | 2 | 04/30/2015 | 05/01/2015| 20 | 25 |

| Test2 | 1 | 05/2/2015 | 05/03/2015| 30 | 35 |

| Test2 | 2 | 05/2/2015 | 05/03/2015| 40 | 45 |

| Test2 | 3 | 05/2/2015 | 05/03/2015| 50 | 55 |

+---------------+-------+--------------+------------+------------+--------+

PHP:

include("connect.php");

if( $conn === false ) {

echo "Could not connect.\n";

die( print_r( sqlsrv_errors(), true));

}

/* Set up and execute the query. */

$sql = "";

$stmt = sqlsrv_query( $conn, $sql);

do {

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {

$json[] = $row;

}

} while ( sqlsrv_next_result($stmt) );

foreach ($json as $result) {

$data[data][][$result['ACTIVITY_NAME']]['children'] = $result;

}

echo json_encode($data);

?>

编辑 –

这是我的工作脚本最终看起来像:

include("connect.php");

if( $conn === false ) {

echo "Could not connect.\n";

die( print_r( sqlsrv_errors(), true));

}

/* Set up and execute the query. */

$sql = " ";

$stmt = sqlsrv_query($conn, $sql);

// This is where the data will be organized.

// It's better to always initialize the array variables before putting data in them

$data = array();

// Get the rows one by one

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {

// Extract the activity name; we want to group the rows by it

$name = $row['ACTIVITY_NAME'];

$group = '';

$sdate = '';

$edate = '';

$completed = '';

$total = '';

$perc = '';

// Check if this activity was encountered before

if (! isset($data[$name])) {

// No, this is the first time; we will make room for it, first

$data[$name] = array(

// Remember the name

'ACTIVITY_NAME' => $name,

'MAINTENANCE_GROUP' => $group,

'START_DATE' => $sdate,

'END_DATE' => $edate,

'COMPLETED' => $completed,

'TOTAL_CLUSTERS' => $total,

'COMPLETE_PERC' => $perc,

// No children yet

'children' => array(),

);

}

// Put the row into the list of children for this activity

$data[$name]['children'][] = $row;

}

// Here, the entries in $data are indexed by the values they also have in 'ACTIVITY_NAME'

// If you want them numerically indexed, all you have to do is:

$data = array_values($data);

echo json_encode(array('data' => $data));

//echo json_encode($data);

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值