0

I am trying to sort query result into an array.

I have following query.

"select s.*, a.* from students left join addresses as a";

it returns

s.id
s.name
a.id
a.student_id
a.address

I would like to make above result into an array with s and a keys.

array(
  "s"=>array("id"=>"value","name"=>"value")
  ,"a"=>array("id"=>"value","student_id"=>"value","address"=>"value)
)

do I have to make my own function to do it or is there an internal function?

4
  • Paolo Bergantino // thanks!. I was about to modify my question :) Commented Jun 4, 2009 at 0:01
  • 1
    No problem; as far as the question, why do you feel the need to do this? Commented Jun 4, 2009 at 0:02
  • I agree with Paolo - why do you need this? Commented Jun 4, 2009 at 0:20
  • I am trying to make model relationship that of cakephp on my own. I need to make left join query that involes more than 2 tables. so...I have to sort each table's fields into array as I asked above. Commented Jun 4, 2009 at 1:30

2 Answers 2

1

Aside: In your current code I believe s.id will get overwritten by a.id if you select rows as associative arrays.

Now, on to one possible approach...

One aspect of how the results are returned is you lose the table from which the column came. If you find yourself wanting to do post-processing on the resultset, perhaps you could alias each column by renaming it like so:

$query = "SELECT
    s.id         AS s_id
    s.name       AS s_name
    a.id         AS a_id
    a.student_id AS a_student_id
    a.address    AS a_address
    ... ";

Once you have that you can organize the data based on substr($key,0,1) and get the "underlying column name with substr($key,2).

Once you have those you can loop inside each row to create the data structure you want to work with.

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

Comments

1

You have to do it yourself if for no other reason than the table isn't identifiable in PHP from the query result. You only get the column name.

1 Comment

This isn't necessarily true - depending on what library he's using to query this data. mysqli, for example, let's you get this info php.net/manual/en/mysqli-result.fetch-field.php

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.