Add Additional Objects to JSON Encoded Array

后端 未结 4 937
名媛妹妹
名媛妹妹 2021-02-06 04:21

I am currently using a JSON encoded array to display the users in my database for an auto-suggest feature.

It looks something like this:

$sth = mysql_que         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 04:45

    I'm not an expert in any of these fields, but I'll try and see if I can help. Try one of these:

    Option 1 (I don't know how unions work in mysql):

    $sth = mysql_query("SELECT id, name FROM users union SELECT id, name FROM (SELECT id, title as name from another_table) as T2"); 
    
    
        $json = array(); 
    
            while($row = mysql_fetch_assoc($sth)) { 
                $json['name'] = $row['name']; 
                $json['id'] = $row['id']; 
            }
    
        $json['name'] = 'A new name';
        $json['id'] = '444';
        $data[] = $json; 
    
        print json_encode($data);
    

    I've never done PHP, so I'm making assumptions. I've also never used MySql, so there's more assumptions.

    Option 2:

    $sth = mysql_query("SELECT id, name FROM users"); 
    
    
        $json = array(); 
    
            while($row = mysql_fetch_assoc($sth)) { 
                $json['name'] = $row['name']; 
                $json['id'] = $row['id']; 
            }
    
    $sth = mysql_query("SELECT id, title from another_table"); 
    
    
            while($row = mysql_fetch_assoc($sth)) { 
                $json['name'] = $row['title']; 
                $json['id'] = $row['id']; 
            }
    
        $json['name'] = 'A new name';
        $json['id'] = '444';
        $data[] = $json; 
    
        print json_encode($data);
    

    Hope this helps.

提交回复
热议问题