如何在php中合并数组并用json编码?

时间:2015-11-09 07:49:06

标签: php arrays json

我有两张桌子。从visit_reports表我得到这个id只有一行,但在reviews_reports我得到2行。

$sql = "select * from visit_reports WHERE visit_planner_id='$id'";
$query = sqlsrv_query( $link, $sql);

$sql2 = "select yes_no_not_app,comments from reviewed_reports WHERE visit_planner_id='$id'";
while($data = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC))
        {
            $val = $data;
        }

    while($data2 = sqlsrv_fetch_array($query2,SQLSRV_FETCH_ASSOC))
        {
            $val2[] = $data2;
        }

    $val4 = array_merge($val, $val2);
    echo json_encode($val4);

从此我得到

{"id":1,"visit_planner_id":230338,"company_name":"ShafiConsultancy","short_title":"SC","report_name":"test report","trial_no":1,"site_id":1,"date_of_report":"11\/05\/2015","date_of_visit" :"11\/05\/2015","date_of_previous_visit":"11\/05\/2015","investigator_name":"rana","investigato   r_address":"shopnil","patient_enrolled":"no","enrolled_discont":"no","patient_entered":"no","entered   _discont":"yes","completed":"yes","cml_name":"test cml","cra_name":"test cra","phone":123456,"fax":123456,"email":"rana@gmail.com"
,"site_staff_present_name":"test staff","site_staff_trial_function":"test    staff     trial","bi_staff_present_name" :"test staff","bi_staff_trial_function":"trest staff trial","0":    {"yes_no_not_app":"Yes","comments":"test comment 1"},"1":{"yes_no_not_app":"no","comments":"test comment 2"}}'

我想要这样

{"id":1,"visit_planner_id":230338,"company_name":"ShafiConsultancy","short_title":"SC","report_name":"test report","trial_no":1,"site_id":1,"date_of_report":"11\/05\/2015","date_of_visit" :"11\/05\/2015","date_of_previous_visit":"11\/05\/2015","investigator_name":"rana","investigato   r_address":"shopnil","patient_enrolled":"no","enrolled_discont":"no","patient_entered":"no","entered   _discont":"yes","completed":"yes","cml_name":"test cml","cra_name":"test cra","phone":123456,"fax":123456,"email":"rana@gmail.com"
,"site_staff_present_name":"test staff","site_staff_trial_function":"test    staff     trial","bi_staff_present_name" :"test staff","bi_staff_trial_function":"trest staff trial",    "yes_no_not_app":"Yes","comments":"test comment 1","yes_no_not_app":"no","comments":"test comment 2"}'    

我想要一个阵列中的所有人。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您不能在一个数组中使用相同的索引名称

检查此行。

while($data = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC))
    {
        $val = $data;
    }

while($data2 = sqlsrv_fetch_array($query2,SQLSRV_FETCH_ASSOC))
    {
        $val2[] = $data2;   <--- array index is added, remove this.
    }