PHP/mySQL - how to fetch nested rows into multidimensinal array

后端 未结 2 1763
心在旅途
心在旅途 2020-12-10 20:22

Coming from another question of mine where I learnt not to EVER use db queries within loops I consequently have to learn how to fetch all the data in a convenient way before

2条回答
  •  伪装坚强ぢ
    2020-12-10 20:27

    The query should look something like this:

    SELECT * FROM scales
    INNER JOIN items ON scales.id = items.scale_id
    

    If you want to iterate through with nested loops, you'll need to pull this data into an array - hopefully you're not pulling back so much that it'll eat up too much memory.

    $scales = array();
    
    while ($row = mysql_fetch_assoc($data))
    {
        if (!isset($scales[$row['scale_id']]))
        {
            $row['items'] = array();
            $scales[$row['scale_id']] = $row;
        }
    
        $scales[$row['scale_id']]['items'][] = $row;
    }
    

    Then you can loop through:

    foreach ($scales as $scale)
    {
        foreach ($scale['items'] as $item)
            ; //... do stuff
    }
    

    Note: this is somewhat naive in that $scale and $item will both contain fields from BOTH tables... if that's a problem then you need to change the assignments in the loop above to pull out only the fields you want.

提交回复
热议问题