开发者

Iterative appending of array with arrays from sql results

开发者 https://www.devze.com 2023-04-09 20:36 出处:网络
am new here, but have enjoyed reading others\' questions and answers. I\'m fairly new to PHP and am working on a project - basic table look-ups in MySQL, etc.

am new here, but have enjoyed reading others' questions and answers. I'm fairly new to PHP and am working on a project - basic table look-ups in MySQL, etc. What I want to end up with is an array of arrays, the form of which is shown below with condiments (not my actual project). The content is coming from two different tables. For each of the condiment names (from table 1) I look up in table 2 the types of condiments, linked by ID. The searching and grabbing stuff is fine, but I'm having trouble looping and building my final $Condiments array.

The first part of the loop, I grab the condiment name from the $row and append it to the array. But I need each of these condiment names to be an empty array to put something in, in the next step. I've looked around but couldn't find a good way to iteratively append new placeholder arrays into an array. Is there an elegant solution? Some cool function I'm not taking advantage of? Thanks!

// SQL search for condiment words, blah blah, leading to...
$rowsnumber = mysql_num_rows($result);

for ($j = 0 ; $j < $rowsnumber ; ++$j)
    {
    $row = mysql_fetch_row($result); // $row is an array featuring a condiment name and other stuff.
    $Condiments[] = $row[1]; // condiment name goes in array.
    $CondimentType = searchTable2($row[0]开发者_如何学Go); 
    // using the condiment name's ID, I look up its matching types via a function.
    // $CondimentType is now an array of IDs and types from Table2 that I want to append to the condiment name I just added above.
        $Condiments[$row[1]] = $CondimentType;
    // I repeat the process for the next name
    }

// Final desired result...
$Condiments=
Array
(
    [Pickles] => Array
        (
            [34] => Dill
            [23] => Butter
        )
    [Mustard] => Array
        (
            [22] => Hot
        )
    [Relish] => Array
        (
            [3] => Pickle
        )
)


so like i said , you need to use join to perform the needed task.

you can find more explanation here about joins

http://dev.mysql.com/doc/refman/5.0/en/join.html

in your case , this query should do the job

select t1.word,t3.word
from table1  as t1  join table2 as t2 on t1.id =t2.id
left join table1 as t3 on t3.id = t2.linkid

i ran the query in my machine and these are the results

+---------+--------+
| word    | word   |
+---------+--------+
| Pickles | Dill   |
| Pickles | Butter |
| Mustard | Hot    |
| Relish  | Pickle |
+---------+--------+

so instead of looping through each row, just perform a join and get the results. in php then you can do the needed format of the array. hopefully this will help you

0

精彩评论

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

关注公众号