簡體   English   中英

使用php將數組數據格式化為JSON_ENCODE

[英]Format Array Data to JSON_ENCODE using php

我正在使用php將數組數據格式化為Json_encode 該數組數據來自我的數據庫。 我已經描述了我如何在這里做

$pens=$db->fetchAllPens();  //This fetches the list of pens
$a = array();
$response = array();

$response["success"]="true";

while ($pen = mysqli_fetch_array($pens)) {    
    $response["label"]["id"]=$pen["ID"];
    $response["label"]["name"] = $pen["name"];

    array_push($a,$response);
}

    echo json_encode($a,JSON_PRETTY_PRINT);

上面的代碼給了我下面的輸出

[
{
    "success": "true",
    "label": {
        "id": "1",
        "name": "nimble"
    }
},
{
    "success": "true",
    "label": {
        "id": "2",
        "name": "lopsel"
    }
}
]

但是我期望下面的輸出

{
"success":true,
"label":[
    {
        "id":1,
        "name":"nimble"

    },
    {
        "id":2,
        "name":"lopsel"

    }
]
}

請有一種方法來達到預期的效果。

$pens = $db->fetchAllPens();  //This fetches the list of pens
$response = array('success' => true, 'label' => array());

while ($pen = mysqli_fetch_array($pens)) {    
    $response['label'][] = array('id'   => $pen['ID'],
                                 'name' => $pen['name']
                                );
}

echo json_encode($response,JSON_PRETTY_PRINT);

在每個循環周期中,您正在寫入錯誤的變量。

而是執行以下操作:

while ($pen = mysqli_fetch_array($pens)) {
  $data[] = [
    'id' => $pen['ID'],
    'name' => $pen['Name'],
  ];
}

$response['label'] = $data;

echo json_encode($response,JSON_PRETTY_PRINT);

首先將status直接放入$a數組中。

然后將行數據放入$a['label'][]$a['label']數組的新出現

$pens=$db->fetchAllPens();  //This fetches the list of pens
$a = array();

$a["success"] = "true";

while ($pen = mysqli_fetch_array($pens)) {    
    $response = array();

    $response["id"]     = $pen["ID"];
    $response["name"]   = $pen["name"];

    $a['label'][]       = $response;
}
echo json_encode($a,JSON_PRETTY_PRINT);

結果:

{
    "success": "true",
    "label": [
        {
            "id": 1,
            "name": "fred"
        },
        {
            "id": 2,
            "name": "Bill"
        }
    ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM