Ricky Mason
Ricky Mason

Reputation: 1828

Can't format my array properly following query

I keep getting this:

[0] => Array
    (
        [0] => Array
            (
                [thread_id] => 136
                [owner_id] => 1
                [subject] => asdhjkasdh
                [body] => askjdhaksjd
                [timestamp] => 2012-03-22 22:03:51
                [slug] => asdhjkasdh
            )

    )
[1] => Array
    (
        [0] => Array
            (
                [thread_id] => 137
                [owner_id] => 1
                [subject] => asdhjkasdh
                [body] => askjdhaksjd
                [timestamp] => 2012-03-22 22:03:56
                [slug] => asdhjkasdh
            )

    )

But I need each [0] and [1] to contain the data, not another array.

Here is my code: The initial query returns the thread_id in array form. I then use the thread_id to pull the info from the thread table. Though I can't seem to organize it correctly in the array.

            $query = $this->db->query($sql);
            $result = $query->result_array();
            $thread = array();
            foreach ($result as $thread_id)
            {
                $id = $thread_id['thread_id'];
                $query = $this->db->query("SELECT * FROM thread WHERE thread_id='$id'");
                array_push($thread, $query->result_array());
            }
            print_r($thread);
            return $thread;

Thanks!

Upvotes: 1

Views: 54

Answers (3)

snaderss
snaderss

Reputation: 139

It is because $query->result_array() will give you an array, even if it has only 1 row in it. After that you push that array into your array ($thread).

If you are sure you will always get one row, you can better use

$row = $query->row();

Maybe add LIMIT 1 to your query to be sure ;)

You can also do

$thread[] = $query->row();

Upvotes: 0

liquorvicar
liquorvicar

Reputation: 6106

It looks like your database object is returning a multi-dimensional array which is being pushed to your $thread array. Instead of

array_push($thread, $query->result_array());

try

$thisRow = $query->result_array();
array_push($thread, $thisRow[0] );

Also it looks like you are running one query, looping through the results and then running another query. This isn't usually a very efficient way of retrieving the data and can usually be refactored using a JOIN. Maybe post your separate queries as a new question so we can help you improve that.

Upvotes: 2

bububaba
bububaba

Reputation: 2870

Use array_merge instead of array_push then

Upvotes: 1

Related Questions