来自数据库的json_encode数据数组

时间:2019-05-10 12:44:10

标签: php jquery mysql ajax

我不确定如何编写以下代码。

    $rowID = $_POST['rowID'];
    if ($listing = $Listings->getData($rowID)) {
        $jsonArray = array(

            'listing_number' => $listing['listing_number'],


        );
        exit(json_encode($jsonArray));
    }

当我这样做时,响应为未定义索引:listing_number。

但是,如果我这样写,

$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
    $jsonArray = array(

        'listing_number' => $listing[0],


    );
    exit(json_encode($jsonArray));
}

响应为

{"listing_number":{"id":"24","client_id":"1","address":"","address_2":"","city":"","state":"","zip":"","price":"","listing_number":"asdasdasdasd","remarks":"","link":"","status":"","bd":"","ba":"","lot_sz":"","sq_ft":"","yr":"","type":"","thumb":""}}

这让我知道我的SQL是正确的,PHP是正确的,只是我不知道如何正确访问$listing['listing_number]

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

正如GrumpCrouton在评论中所说,您的查询正在返回结果数组。因此,如果要在第一个结果中访问值,则首先需要使用其索引来访问该结果:
$listing[0]->listing_number

$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
    $jsonArray = array(
        'listing_number' => $listing[0]->listing_number,
    );
    exit(json_encode($jsonArray));
}

P.S。您可以使用简单的强制转换($result = (array) $result)将对象转换为数组,但这并不是必须的。将对象强制转换为数组将允许您使用result['key']而非result->key访问其数据。