0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oooh, you got there just before me :)
Hmm I didn't know that, so that's why I was getting an object and the number as string instead of as an integer... Thanks! (I'll accept in 3 min)
0

$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.

4 Comments

Since when was mysqli depreciated?
My bad, got muddle up with mysql_* functions
PDO is still better :)
mysqli is not depecreated but I'm thinking on making the switch once I have the time to learn about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.