简体   繁体   中英

foreach inside while loop not work

Im trying to display a list of cars with specifications: weight, length, width.
Everything would be inside a foreach and inside a while, but I cant run it properly...

My tables
cars:
idcar: 1 / width:30 / length:10 / weight:300
idcar: 2 / width:20 / length:12 / weight:210
idcar: 3 / width:20 / length:21 / weight:230
idcar: 4 / width:40 / length:11 / weight:210

and specs table:
idspec:1 spec:width
idspec:2 spec:weight
idspec:3 spec:length

And my code

    $idcar = $_GET['idcar'];
    $resultcarfirst = mysqli_query($connecDB,"select * from products order by (case idcar when $idcar then 0 else idcar end), $idcar asc");
    $resultspec = mysqli_query($connecDB, "SELECT * FROM specs ORDER BY idspec");
    
    while($rowspec = mysqli_fetch_array($resultspec)){
            echo '<div><h1>'.$rowspec["spec"].'</h1><br/>';
    
            $arraycars = array();
            while($rowcar = mysqli_fetch_array($resultcarfirst))
            $arraycars[] = $rowcar;
            foreach($arraycars as $rowcar){
                echo '<p>idcar:'.$rowcar['idcar'].' '.$rowspec['spec'].': '.$rowcar[$rowspec['spec']].'</p>';
            }
    
            echo '</div><br/>';
        }
    

    The output would be:
    Width
    idcar:1 width:30
    idcar:2 width:20
    idcar:3 width:20
    idcar:4 width:40

    Weight
    idcar:1 weight:300
    idcar:2 weight:210
    idcar:3 weight:230
    idcar:4 weight:210

    Length
    idcar:1 length:10
    idcar:2 length:12
    idcar:3 length:21
    idcar:4 length:11

    Thank you and i hope I was clear.

    WHy would you do this..??

    All you need is...

        $arraycars = array();
        while($rowcar = mysql_fetch_array($resultcarfirst)){
        echo '<p>idcar:'.$rowcar['idcar'].' '.$rowspec['name'].':    '.$rowcar[$rowspec['spec']].'</p>';
        $arraycars[] = $rowcar;}
    

    Unless Im completely misunderstanding what you want to do.?

    Also...if you wanna pull the sspecs only for that car....with that while loop, then you have to change your query to accept a variable from the first while loop, if you know what I mean

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM