Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing output structure of MySQL query without using PHP

Tags:

database

mysql

I am currently querying a MySQL database for data and getting results back in PHP.

I am running the query

SELECT title.id, title.title, title.description
FROM co_titles title
WHERE title.id = :title

And I am getting the result back as follows:

Array ( 
    [0] => Array ( 
        [id] => 1966 
        [title] => Example Title 
        [description] => Example Description
    )
)       

There is nothing wrong with the query and this is the exact result I expect, however I would like my result to look like this:

Array (
    [1966] => Array (
        [title] => Example Title 
        [description] => Example Description
    )
)   

SEE EDIT BELOW, this is no longer relevant: Is there a way I can modify my query in order to make the output look like this? I want to do this without using PHP, only MySQL, unless this is completely impossible in MySQL!

I thank you all very much for your help, I have been banging my head against a wall on this one.

EDIT: Okay it seems that basically what I was trying to do was impossible. Could someone assist with the most efficient way of converting from one to the other?

Okay I figured it out, for anyone after me, the best way I found was as follows:

function parseNotes($notes)
{
    $returnarray = array();
    foreach($notes as $i)
    {
        $returnarray[$i['id']] = $i;
        unset($returnarray[$i['id']]['id']);
    }
    return $returnarray;
}

Thank you all for your help!

like image 520
theother404 Avatar asked Apr 19 '26 18:04

theother404


1 Answers

You can't. The records returned by the query is linear. The only way to do that is by formating it in your PHP code. MySQL is a server a has no capability to do that even if you use GROUP BY.

like image 154
John Woo Avatar answered Apr 21 '26 09:04

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!