如何使用PHP获取数组中json的记录?

时间:2017-01-09 16:03:22

标签: php mysql arrays json rest

$emparray=array();
    while($row = mysqli_fetch_array($result,MYSQL_NUM))
    {
        foreach ($row as $key => $value)
        {
            if ($value == '')
            {
                $row[9] ='We follow-up you';
            }
        }
        $emparray[] = array
         ('success' => true,
          'message' => "audio saved Successfully!",
         array('client_cname' => $row[2],
            'future_followup' => $row[8],
            'notes' => $row[9]));             

    }                

**如上所示,这是我使用while循环从db获取记录的代码。 问题是我得到所有记录,但与不同的arrys。我希望它只有一个索引**

的数组
    [
    {
        "success": true,
        "message": "audio saved Successfully!",
        "0": {
            "client_cname": "Hhhs",
            "future_followup": "4 Jan 2017 05:17 PM",
            "notes": "hey"
        }
    },
    {
        "success": true,
        "message": "audio saved Successfully!",
        "0": {
            "client_cname": "Hcjc",
            "future_followup": "4 Jan 2017 06:17 PM",
            "notes": "hey"
        }
    }
]

以上是我的O / P

我希望它以下面的格式请帮助我。

{
    "status": "true",
    "message": "Audio Saved successfully!"
   [
     {
            "client_cname": "Atul",
         “future_followup": “”,
         “notes": “”,
     },
    {
            "client_cname": "Atul",
         “future_followup": “”,
         “notes": “”,
     }
   ]
}

如果我从$ emparray中删除 - > [],那么我将只获得如下代码的最后一行代码

{
    "success": true,
    "message": "audio saved Successfully!",
    "0": {
        "client_cname": "Hcjc",
        "future_followup": "4 Jan 2017 06:17 PM",
        "notes": "hey"
         }
}

但我希望这种结果带有索引0,1,2等等。

请帮我一样。提前谢谢。

2 个答案:

答案 0 :(得分:0)

以下是您需要做的事情:

if(mysqli_num_rows($result)>0) { //if there are any results
  //initialise the array with the first two values
  $emparray = array(
    'success' => true,
    'message' => "audio saved Successfully!");
}

while($row = mysqli_fetch_array($result,MYSQL_NUM))
{
    foreach ($row as $key => $value)
    {
        if ($value == '')
        {
            $row[9] ='We follow-up you';
        }
    }

     //append each data item as an array
     $emparray[] = array('client_cname' => $row[2],
        'future_followup' => $row[8],
        'notes' => $row[9]));             

}        

这也将从0开始以数字方式自动索引所有其他数组。

答案 1 :(得分:0)

May be this is more better way to deal with.

$dataSet = array();
    while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
        foreach ($row as $key => $value) {
            if ($value == '') {
                $row[9] = 'We follow-up you';
            }
        }
        $dataSet[] = array('client_cname' => $row[2],
            'future_followup' => $row[8],
            'notes' => $row[9]);
    }

    $emparray = array
    ('success' => true,
        'message' => "audio saved Successfully!",
        'data' => $dataSet);
    echo json_encode($emparray);