开发者

How to pull data from sub-array, and combine

I do a database call to list all the "categories" that bel开发者_如何学运维ong to a user. This returns to me an array, with sub-arrays with specific data on each category.

How do I pick out the category IDs from these, and combine them to form a new query that grabs all the posts in these categories?


Tables: "assignments" and "classes".

Assigments: assignmentid, classid, ...

Classes: classname, userid, ...

Here's the code I'm using.

$query = dbquery("SELECT classid, classinfo FROM classes WHERE userid = 1");

This returns to me an array with subarrays:

Array ( 
[0] => Array ( [classid] => 2 [classinfo] => classinfo )
[1] => Array ( [classid] => 3 [classinfo] => classinfo ) 
...

How would I extract out all the classids, and then list them as "2 OR 3 OR ..." for use in another MySQL query?


You don't really have to do that (get the classids in PHP and then send another query). You could simply use the query you have with something like:

SELECT assignments.assignmentid      
     , assignments.classid
     , assignments.otherfield
FROM assignments
WHERE assignments.classid IN 
  ( SELECT classid, classinfo
    FROM classes
    WHERE userid = 1
  )

or

SELECT assignments.assignmentid      --- or whatever fields you want
     , assignments.classid           --- from table assignments
     , classes.classinfo           --- or table classes
FROM assignments
  JOIN classes
    ON assignments.classid = classes.classid
WHERE classes.userid = 1  

Both these queries will show almost same results (if you remove the classes.classinfo from the second query, the results will be identical). That is, all assignments data that are related to a class with userid = 1.


There are numerous SQL tutorials on the web. You can try for example: w3schools.com


foreach over the array of categories, building a new array or simple string that you can include in a post query.

That's about all I can say, without having some specific code to critique. Though, sounds like something you could do completely in SQL. (May or may not be applicable depending on your caching needs.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜