在JSON上添加'total'属性

时间:2015-04-20 04:46:06

标签: php json

在我的项目中,我从数据库中获取数据行,并使用json_encode将数据转换为JSON。我正在回应JSON,到目前为止它正在显示正确的结果。这是一个示例:

{"results":[{"id":"1","name":"test name","description":"test description","db_hostname":"test hostname","db_schema":"test schema","email":"test@yahoo.com"}]}

现在,我想在“结果”之前插入一个“总计”。 'total'是结果的总条目。这将是结构:

{"total":"1", "results":[{"id":"1","name":"test name","description":"test description","db_hostname":"test hostname","db_schema":"test schema","email":"test@yahoo.com"}]}

'total'的值会根据“结果”的项目数而变化。我如何在PHP中执行此操作?

2 个答案:

答案 0 :(得分:1)

使用json_encode()json_decode()来实现这一目标:

<?php
  $obj = '{"results":[{"id":"1","name":"test name","description":"test description","db_hostname":"test hostname","db_schema":"test schema","email":"test@yahoo.com"}]}';
  $arr = json_decode($obj, true);

  $new_obj = json_encode( array_merge(array("total"=>count($arr['results'][0])), $arr ) );
  print_r($new_obj);

<强> DEMO

答案 1 :(得分:0)

所以我相信下面的代码应该有效(如果我理解你正在尝试做的事情):http://jsfiddle.net/obfa34mb/

var results = [
{"results":[{"id":"1","name":"test name","description":"test description","db_hostname":"test hostname","db_schema":"test schema","email":"test@yahoo.com"}, {"id":"2","name2":"test name2","description2":"test description2","db_hostname":"test hostname","db_schema":"test schema2","email2":"test2@yahoo.com"}]},
{"results":[{"id":"3","name3":"test name3","description3":"test description3","db_hostname":"test hostname","db_schema":"test schema","email":"test3@yahoo.com"}, {"id":"4","name4":"test name4","description4":"test description","db_hostname":"test hostname","db_schema":"test schema4","email4":"test4@yahoo.com"}]},    
];

var new_results = [];
for (var i = 0; i < results.length; i++) {
    var item = {
        'total': results[i].results.length,
        'results': results[i].results
    };
    new_results.push(item);
}
console.log(new_results);