使用PHP从MYSQL获取一些数据到JSON

时间:2017-12-12 09:14:22

标签: php json mysqli

看我在我的数据库中有这个表 enter image description here

db code

CREATE TABLE `tbl_employee` (
  `employee_id` int(4) NOT NULL,
  `employee_name` varchar(60) NOT NULL,
  `designation` varchar(30) NOT NULL,
  `hired_date` date NOT NULL,
  `salary` int(10) NOT NULL,
  `supervised` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO tbl_employee (employee_id,employee_name,designation,hired_date, salary, supervised) VALUES
(5901, 'Alex', 'VP', '2013-08-01', 60000, ''),
(5902, 'Lim', 'Executive', '2014-10-09', 20000, 'VP'),
(5903, 'John', 'Manager', '2013-08-20', 40000, 'VP'),
(5904, 'Ali', 'Asst. Manager', '2013-06-01', 25000, 'Manager'),
(5905, 'Julia', 'Trainee', '2014-10-01', 10000, 'Supervisor'),
(5906, 'Robert', 'Engineer', '2017-12-01', 12000, 'Supervisor');

我想选择几个要插入json的列,json应该是这样的

'name': 'Master',
      'title': 'VP : $60000',
      'children': [
        { 'name': 'Lim', 'title': 'Executive : $20000'},
        { 'name': 'John', 'title': 'Manager : $40000',
          'children': [
            { 'name': 'Ali', 'title': 'Asst. Manager : $25000' }
          ]
        },
        { 'name': 'Yuu', 'title': 'Supervisor : $18000' ,
            'children':[
                { 'name': 'Julia', 'title': 'Trainee : $10000'},
                { 'name': 'Robert', 'title': 'Engineer : $12000'}
            ]
        }
      ]

这是我的PHP代码,

$sel_query = mysqli_query($conn,"SELECT * FROM `tbl_employee` where employee_id='".$userid."'") or die("Error in Selecting " . mysqli_error($conn));
$arrResult = array();
while($res = mysqli_fetch_assoc($sel_query)){
    $arrResult[] = $res;
} 
echo json_encode($arrResult);
mysqli_close($conn)

但是我得到了这样的完整数据     [{ “EMPLOYEE_ID”: “5901”, “employee_name”: “亚历克斯”, “名称”: “VP”, “hired_date”: “2013年8月1日”, “工资”: “60000”, “监督”: “”}]

所以如何实现我想要的,请帮助.. 感谢

3 个答案:

答案 0 :(得分:1)

尝试按照以下代码。你会得到期待的结果。

$sel_query = mysqli_query($conn,"SELECT * FROM `tbl_employee` where employee_id='".$userid."'") or die("Error in Selecting " . mysqli_error($conn));

$staff_query = mysqli_query($conn,"SELECT employee_name as name, CONCAT(designation,':',salary) as title FROM `tbl_employee` where employee_id!='".$userid."' and designation!='VP'") or die("Error in Selecting " . mysqli_error($conn));

 $staff_array = mysqli_fetch_assoc($staff_query);

$arrResult = array();
while($res = mysqli_fetch_assoc($sel_query)){
    $arrResult['name'] = $res["employee_name"];
    $arrResult['title'] = $res["designation"]. " : ".$res["salary"];
    $arrResult['staff'] = $staff_array;
} 
echo json_encode($arrResult);
mysqli_close($conn);

注意:根据您的结果,我没有获得员工信息栏,这就是为什么我只给出了名称和头衔的例子。

答案 1 :(得分:1)

您可以从数据库中执行两个SELECTS:

$sel_query = mysqli_query($conn,"SELECT * FROM `tbl_employee` where employee_id='".$userid."'") or die("Error in Selecting " . mysqli_error($conn));
$res = mysqli_fetch_assoc($sel_query)
$jsonResult = array(
        "name" => $arrResult['name'],
        "title" => $arrResult['title'] = $res["designation"]. " : ".$res["salary"],
        "staff" =>array(),
    );
$sel_query = mysqli_query($conn,"SELECT * FROM `tbl_employee` where supervised='".$res['designation']."'") or die("Error in Selecting " . mysqli_error($conn));
$res = mysqli_fetch_assoc($sel_query);//corrected
$i = 0;
while($res = mysqli_fetch_assoc($sel_query)){
    $jsonResult['staff'][$i++] = array(
        ['name'] => $res["employee_name"],
        ['title'] => $res["title"],
        $res["designation"]. " : ".$res["salary"],
        );
} 
echo json_encode($jsonResult);
mysqli_close($conn);

答案 2 :(得分:1)

对于您的问题,您需要将您的数据整理为树级别。

逻辑(最小化数据库连接,但使用额外的RAM进行处理)

  1. 从数据库获取所有数据并按supervised
  2. 排序
  3. 找出Master的人,supervised很可能是空的
  4. 递归supervised
  5. 查找人的孩子(工作人员)

    编码

    // step 1
    $sel_query = mysqli_query($conn, "SELECT * FROM `tbl_employee` Order by supervised ASC") or die("Error in Selecting " . mysqli_error($conn));
    $arrResult = array();
    while($res = mysqli_fetch_assoc($sel_query)){
        $arrResult[] = $res;
    } 
    mysqli_close($conn);
    
    
    //step 2
    $master = array();
    for($i=0; $i<count($arrResult); $i++){
        if( empty($arrResult[$i]['supervised']) ){
            $master = $arrResult[$i];
            //unset($arrResult[$i]); //remove himself, buggy, use next line
            array_slice($arrResult, $i, 1); //remove himself
            break;
        }
    }
    
    
    $output = standardFormat($master);
    
    
    //step 3
    $masterChilds = findChilds($arrResult, $master['designation']);
    $output['children'] = $masterChilds;
    
    
    //$records is passing-by-reference
    //http://php.net/manual/en/language.references.pass.php
    function findChilds( &$records, $parentPosition ){
        if( count($records) <= 0 ){
            return array();
        }
        $childs = array();
        for($i=0; $i<count($records); $i++){
            if( $records[$i]['supervised'] == $parentPosition ){
                $child = standardFormat($records[$i]);
                $childPosition = $records[$i]['designation'];
                //unset($records[$i]); buggy, use next line
                array_slice($records, $i, 1);
                //$childOfChilds = findChilds( &$records, $childPosition );//buggy, use next line
                $childOfChilds = findChilds( $records, $childPosition );
                if( count($childOfChilds) > 0 ){
                    $child['children'] = $childOfChilds;
                }
                array_push($childs, $child);
            }
        }
        return $childs;
    }
    
    function standardFormat($dbrow){
        $output = array();
        $output['name'] = $dbrow['employee_name'];
        $output['title'] = $dbrow['designation'] . ' : $' . $dbrow['salary'];
        return $output;
    }
    
    echo json_encode($output);
    

    PS:测试没有错误和预期结果&amp;格式。