php以JSON形式回显多维数组

时间:2016-02-18 01:23:42

标签: java php arrays json list

我正在尝试以JSON形式在array表单中显示数据库中的所有用户。这就是我所拥有的 - 但它不是我想要的形式

{
  "username": [
    "bobgreen",
    "jacksmitd",
    "samson",
  ]
  "forename": [
    "Bob",
    "Jack",
    "Sam",
  ],
  "surname": [
    "O'Conor",
    "Smitd",
    "Son",
  ]
}

这是我提供此输出的代码......

if(mysqli_num_rows($outcome)){
    while($row = mysqli_fetch_assoc($outcome)){
        $finalOutcome["username"][] = $row["username"];
        $finalOutcome["forename"][] = $row["forename"];
        $finalOutcome["surname"][] = $row["surname"];
    }
    echo json_encode($finalOutcome); 
}

我想将所有相关细节存储在大括号内,如:

{
    "username":"bobgreen"
    "forename":"Bob"
    "surname":"O'Conor"
}
{
    "username":"jacksmitd"
    "forename":"Jack"
    "surname":"Smitd"
}
{
    "username":"samson"
    "forename":"Sam"
    "surname":"Son"
}

另外,如何从每个大括号中提取所有相关数据并存储在Java列表中?因为我试图在每个用户的基础上存储所有细节,所以我不确定如何使用我的第一个JSON数组

2 个答案:

答案 0 :(得分:1)

关于主要问题:

您必须使用以下语法:

while( $row = mysqli_fetch_assoc( $outcome ) )
{
    $finalOutcome[] = array
    (
        "username" => $row["username"],
        "forename" => $row["forename"],
        "surname"  => $row["surname"]
    );
}
echo json_encode( $finalOutcome );

基本上,在原始查询中,您会增加$finalOutcome个子数组,而不是$finalOutcome

答案 1 :(得分:0)

你可以做一个更好的解决方案(与问题代码相比):

if(mysqli_num_rows($outcome)){
while($row = mysqli_fetch_assoc($outcome)){

    $userId = $row["id"];
    $finalOutcome[$userId]["username"] = $row["username"];
    $finalOutcome[$userId]["forename"] = $row["forename"];
    $finalOutcome[$userId]["surname"] = $row["surname"];
}
echo json_encode($finalOutcome); 

输出将是:

[
    {
        "username":"username0",
        "forename":"forename0",
        "surname":"surname0"
    }, 
    {
        "username":"username1",
        "forename":"forename1",
        "surname":"surname1"
    }
]