echo json获取std对象的更多值

时间:2015-05-13 14:53:49

标签: php mysql json codeigniter

我有下面的代码检查表是否值为NULL或不是NULL然后回显消息来查看告诉用户该值已经存在,

在此代码中,进行多选输入,然后在mysql数据库中检查所选的id,如果该id有值,则代码将向用户发送错误消息,如果value为NULL,则将继续进行进一步的操作,如add

foreach($this->input->post('sla_department') as $department_id)
        {
            $departmentslacheck = $this->model_admin->checkdepartmentsla($department_id);

            if($departmentslacheck->sla_id !==  NULL)
            {
                echo json_encode(array('cival'=>0, 'val_message' => 'SLA already assigned to '.$departmentslacheck->department_name));

            }                   
        }

我的问题是,当用户在HTML视图中选择2个或更多值并且两者都在数据库表中有值(表示非NULL)时,它会发送2个JSON,这是视图不期望的,所以我看不到错误消息,

有了这个我得到JSON如下,

0: {cival: 0, val_message: "SLA already assigned to X"}
1: {cival: 0, val_message: "SLA already assigned to Y"}

我怎能回应...

cival'=>0, 'val_message' => 'SLA already assigned to X , Y.

其中X和Y是数据库department_name

2 个答案:

答案 0 :(得分:3)

不要在某个条件下立即回显JSON,而是编译最终结果,然后发送它。

$result = [];
foreach($this->input->post('sla_department') as $department_id)
{
        $departmentslacheck = $this->model_admin->checkdepartmentsla($department_id);

        if($departmentslacheck->sla_id !==  NULL)
        {
            $result[] = $departmentslacheck->department_name;

        }                   
}

if (count($result) > 0)
{
    echo json_encode(array('cival'=>0, 'val_message' => 'SLA already assigned to '.implode(', ', $result)));
}

答案 1 :(得分:0)

在开始foreach循环之前初始化一个数组, 将数组insde de loop推送到此数组并回显唯一 主阵列的json_encode:

 $result = array();
foreach($this->input->post('sla_department') as $department_id)
    {
        $departmentslacheck = $this->model_admin->checkdepartmentsla($department_id);

        if($departmentslacheck->sla_id !==  NULL)
        {
           $result[]=array('cival'=>0, 'val_message' => 'SLA already assigned to '.$departmentslacheck->department_name);

        }                   
    }
echo json_encode($result);