JSON使用MySql的对象数组

时间:2016-01-25 14:07:17

标签: php json mysqli

我想从国家数据库中获取此输出。我使用了mysqli_fetch_object()函数,但它不适用于我

"countries":[{"countryname":"India","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/india.png","language":"Hindi","capital":"New Delhi","currency":{"code":"INR","currencyname":"Rupee"}},{"countryname":"Pakistan","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/pakistan.png","language":"Urdu","capital":"Islamabad","currency":{"code":"PKR","currencyname":"Pakistani Rupee"}}]}

我正在使用这个php脚本

<?php
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
    if(!$con)
{
die ("Erro in connection" . mysqli_connect_error);

}
else{     $encode = array();



$sql="select * from country ";
    $res=mysqli_query($con,$sql);

    if(mysqli_num_rows($res)>0)
    {

        $temp_array=array();
        while($row=mysqli_fetch_object($res))
        {

           //$temp_array[]=$row;
            $encode=$row;


        }

        //echo json_encode($temp_array);
        echo json_encode($encode);

    }

    else
    {
    echo " 0 Rows";
    }
}


?>

如果有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您的代码应如下所示;

<?PHP
    require 'config.php';
    $con=mysqli_connect($servername,$username,$password,$db);
    if(!$con)
        die ("Error in connection" . mysqli_connect_error);
    else{
        $encode = array();

        $sql = "select * from country ";
        $res = mysqli_query($con,$sql);
        if(mysqli_num_rows($res)>0)
        {

            $temp_array=array();
            while($row=mysqli_fetch_object($res))
            {
                $encode[]=$row;
            }
        }
        echo json_encode($encode);
    }
?>

你不需要写下0行,因为你要返回一个有一个数组的json对象,所以当你检查 result.length 时它会告诉你行数。

作为建议,您可以使用以下内容;

<?php
    require 'config.php';
    $con = mysqli_connect($servername,$username,$password,$db);
    $resultArray = array();
    $resultArray["error"] = true; //That will tell your javascript client if any error exits.
    $resultArray["errorMessage"] = ""; //We will set this value if any error exits;
    if(!$con)
    {
        $resultArray["error"] = true;
        $resultArray["errorMessage"] = "Error in connection" . mysqli_connect_error();
    }
    else{
        $resultArray["error"] = false;
        $itemCollection = array();

        $sql = "select * from country ";
        $res = mysqli_query($con,$sql);
        if(mysqli_num_rows($res)>0)
            while($row = mysqli_fetch_object($res))
                $itemCollection[]=$row;

        $resultArray["itemCollection"] = $itemCollection;
    }

    echo json_encode($resultArray);
?>

在我的示例中,您将得到类似下面的json结果;

{"error":true,"errorMessage":"ErrorMessageIfExists","itemCollection":[yourObject,yourObject]}

希望这会对你有所帮助。