Chazy Chaz
Chazy Chaz

Reputation: 1851

array creates object with index name of variable

I'm trying to create an array with two arrays inside it but when I print it or convert it to json I get an object with the index name of the variable I used to create the sub-arrays.

    $var1 = [];
    $var2 = [];

    if ($stmt = $mysqli->query('SELECT id FROM table1')) {
        while($id = $stmt->fetch_object()) {
            $var1[] = $id;
        }
        $stmt->close();
        unset($id);
    }

    if ($stmt = $mysqli->query('SELECT id FROM table2')) {
        while($id = $stmt->fetch_object()) {
            $var2[] = $id;
        }
    }

    return array($var1, $var2);

When I print it var_dump($result);:

array(2) { [0]=> array(1) { [0]=> object(stdClass)#14 (1) { ["id"]=> string(1) "1" } } [1]=> array(0) { } }

Why is there an object with the index name id?

I just need a simple array containing 2 subarrays and print them inside two select elements:

    $.get('/get?op=4', function (data) {
        var content = data,
            sale    = content[0],
            rent    = content[1];
            alert(sale);
        $('select[name="lists-sale"]').html(sale);
        $('select[name="lists-rent"]').html(rent);
    });

I echo and encode in json what is returned from the function in the /get?op=4 file.

Upvotes: 0

Views: 39

Answers (2)

MajorCaiger
MajorCaiger

Reputation: 1913

$stmt->fetch_object() fetches an object containing your results.

The object represents the entire row you are selecting, not an individual column.

If you were selecting multiple columns, your object would contain multiple properties.

Upvotes: 0

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40919

You're calling $stmt->fetch_object() and you get what you ask for - an object that represents a row of data returned from the database.

Replace

while($id = $stmt->fetch_object()) {
  $var1[] = $id;
}

with

while($row = $stmt->fetch_object()) {
  $var1[] = $row->id;
}

to get an array of IDs.

Upvotes: 3

Related Questions