简体   繁体   中英

How to merge array in php and encode by json?

I have two tables. From visit_reports table i get just one row for this id but in reviewed_reports I get 2 rows.

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

from this i get

{"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"}}'

I want like this

{"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"}'    

I want to all in one array. How could I do this ?

you cannot have same index names in one array

Check this rows.

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.
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM