Php 添加';总计';JSON上的属性

Php 添加';总计';JSON上的属性,php,json,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"}]} 现在,我想在“结果”之前插

在我的项目中,我从数据库中获取数据行,并使用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":"1", "results":[{"id":"1","name":"test name","description":"test description","db_hostname":"test hostname","db_schema":"test schema","email":"test@yahoo.com"}]}
“总计”的值根据“结果”的项目数而变化。如何在PHP中实现这一点?

使用并实现这一点:

<?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);

因此,我相信以下代码应该可以工作(如果我理解您试图正确执行的操作):

var结果=[
{“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新_结果=[];
对于(var i=0;i
在JSON对象中,顺序是不相关的,因为访问是通过键进行的,很少使用顺序。您可以直接访问“results”length
object.results.length
这并没有回答问题:“我如何在PHP中做到这一点?”这并没有回答问题:“我如何在PHP中做到这一点?”问题是在Javascript中提出的(即:OP询问如何在Javascript中获得结果),因此这是您在PHP或ASP.NET中实现这一点的方式,或者别的什么。服务器端技术与此无关。
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);