KevinM1990112qwq
KevinM1990112qwq

Reputation: 735

json_encode array of data from DB

I am not sure how to write the following code.

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

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


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

When I do it like that, the response is Undefined Index: listing_number.

However, If I write it like this,

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

        'listing_number' => $listing[0],


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

The response is

{"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":""}}

Which lets me know my SQL is and PHP is correct, I just don't know how to access $listing['listing_number] correctly.

Any help would be appreciated.

Upvotes: 0

Views: 46

Answers (1)

Nicolas
Nicolas

Reputation: 8670

as GrumpCrouton said in the comment, your query is returning an array of results. So if you want to access a value in the first result, you first need to access this result using it's index :
$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. You can convert object to array using a simple cast ( $result = (array) $result ), but it is not a must in your case. Casting your object to array will allow you to acces it's data using result['key'] rather than result->key.

Upvotes: 1

Related Questions