如何通过json_encode从foreach循环中提取值

时间:2016-08-25 06:03:56

标签: php jquery json

我有php结果集,从这些结果我使用php foreach循环提取值。我将foreach循环值放在数组$summery[]中。但是当我尝试立即打印其打印值时。但我需要为每个foreach循环单独的值/结果集作为json代码,以便我可以单独打印每个结果。我的foreach循环如下:

foreach($result_UserWrSet as $UserWrInfo) {
        $summery[]=$UserWrInfo['wr_id'];
        $summery[]=$UserWrInfo['wr_number'];
        $summery[]=$UserWrInfo['wr_title'];
        $dateFlag=1;
        $result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
        $result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
        $summery[]=$result_StartDate;
        $sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
        $result_GetUserName = mysqli_query($conn, $sql_GetUserName);
        $num_GetUserName = mysqli_num_rows($result_GetUserName);
        if ($num_GetUserName > 0){
            $UserNameByIdRos = $result_GetUserName->fetch_assoc();
            $UserNameById=$UserNameByIdRos['user_name'];
        }
        else {$UserNameById=NULL;}
        $summery[]=$UserNameById;
        $result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
        $result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
        $summery[]=$result_CurrentHopName;
        $result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
        $summery[]=$result_EndDate;
    }
print json_encode($summery);

我的结果变成了

["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done","01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]

但我需要:

[["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done"],["01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]]

3 个答案:

答案 0 :(得分:1)

使用此代码,您需要使用另一个数组,在该数组中推送所有子数组并在将所有项目推入其中后对该数组进行编码

NSDictionary *Dic= @{@"Name":@"abc",@"ID":@"123"};

答案 1 :(得分:1)

您需要一个多维数组,您可以按照以下代码:

$result_UserWrSet = array(
 '0' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'),
 '1' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'));

foreach($result_UserWrSet as $key => $UserWrInfo) {
    $summery[$key][]=$UserWrInfo['wr_id'];
    $summery[$key][]=$UserWrInfo['wr_number'];
    $summery[$key][]=$UserWrInfo['wr_title'];
}

print json_encode($summery);
output: [["12","785","title1"],["12","785","title1"]]

祝你好运:)

答案 2 :(得分:0)

目前,您只是将新项目添加到一维数组中。您需要为每个结果创建一个单独的数组,如下所示:

foreach($result_UserWrSet as $UserWrInfo) {
    $item = array();

    // Change all $summary in the loop to: $item, like this:
    $item[]=$UserWrInfo['wr_id'];
    $item[]=$UserWrInfo['wr_number'];
    $item[]=$UserWrInfo['wr_title'];

    //...and so on

    // Then add this last in your loop:
    $summary[] = $item;
}

这会在每次迭代中创建一个数组,放在主数组中,然后变成一个多维数组。