【问题标题】:making json object with array in php在php中用数组制作json对象
【发布时间】:2014-10-01 04:24:49
【问题描述】:

我有一些数据库查询。 最后我需要一个像这样的json对象

[{ 活动类型:'发展', 花时间:[ {user:'User1', time:'21'}, // (!) 此用户和此活动的时间量 {用户:'User2',时间:'2'}, ], 总花费时间:23 },{ 活动类型:'设计', 花时间:[ {用户:'用户',时间:'14'}, ], 总花费时间:14 }]

这是我的 sql 查询的 while 循环

while($row = $result->fetch_assoc()){ $data[$row['activity_type']] = array('spent_time' => array('user' => (object)$row['user'])); $data[$row['activity_type']]['spent_time']['user']->time += $row['spent_time']; }

但在结果数组中我有

[设计] => 数组 ( [花费时间] => 数组 ( [用户] => 标准类对象 ( [标量] => 约翰 [time] => 1.5 // (!) 仅是最后一次活动时间,而不是本次活动所用时间的总和 ) ) ) [开发] => 数组 ( [花费时间] => 数组 ( [用户] => 标准类对象 ( [标量] => 尼克 [time] => 0.3 // (!) 仅是最后一次活动时间,而不是本次活动所用时间的总和 ) ) )

如何在循环中为当前用户和当前活动求和时间值?

UPD 这是查询

$sql = "SELECT 
                distinct(projects.name) as project,
                time_entries.hours as spent_time,
                enumerations.name as activity_type,
                versions.name as version,
                users.lastname as user
                FROM  `projects` 
                INNER JOIN time_entries ON ( time_entries.project_id = projects.id ) 
                INNER JOIN enumerations ON ( time_entries.activity_id = enumerations.id ) 
                INNER JOIN versions ON ( projects.id = versions.project_id ) 
                inner join users on (time_entries.user_id = users.id)
                where (projects.identifier = 'test')"; 

【问题讨论】:

  • 当您可以简单地创建一个关联数组来解决问题时,为什么还要将对象和数组混合在一起。
  • 因为它不会对花费时间的值求和,是吗?
  • 你的 json 无效
  • 那个“json”只是举例

标签: php sql arrays json


【解决方案1】:

也许是……

    class ActivityList{
        private $activities;

        public function __construct(){
            $this->activities=array();
        }

        public function addActivity($row){
            //read the row, search for the activity
            //if does not exist, create a new activity
            //if does, get it and use addUser to add more time
            ...
        }
    }

    class Activity{
        private $activity_type;
        private $spent_time;
        private $total_spent_time;

        public function __construct(){
            $this->spent_time=array();
            $this->activity_type="";
            $this->total_spent_time=0;
        }

        public function addUser($user, $timeSpent){
            //search for the user in spent_time
            //if not exist, create a new user
            //if exist, add the time
            //once added, take the time and add to total_spent_time
            ...
        }
    }

    class UserObject{
        private $user;
        private $time;

        public function __construct(){
            $this->user="";
            $this->time=0;
        }
    }

【讨论】:

    猜你喜欢
    • 2015-02-15
    • 1970-01-01
    • 2021-12-13
    • 2011-12-24
    • 2018-10-27
    • 2016-05-08
    • 1970-01-01
    相关资源
    最近更新 更多