简体   繁体   中英

PHP While Loop for Multidimensional Arrays

So i tried to loop through bunch of arrays using the while loop. So it does not work like this, how does it work?

    while($x<$sQuery($SERVER)['number'])
    {
        $o = $o . "<Server>
      <Name>".$sQuery($SERVER)[$x]['name']."</Name>
      <DNS>".$sQuery($SERVER)[$x]['ip']."</DNS>
    <Lat>0</Lat>
      <Long>0</Long>
      <Usage>-1</Usage>
      <RankRequired>0</RankRequired>
    </Server>"
        x++;
    }
}

The error is in this line(s):

      <Name>".$sQuery($SERVER)[$x]['name']."</Name>
      <DNS>".$sQuery($SERVER)[$x]['ip']."</DNS>

The [$x] is not allowed and i do not know how i can loop through them, any ideas?

I would rewrite it this way:-

$s = $sQuery($SERVER);

for($i=0; $i<$s['number']; $i++)
{
    $o .= "<Server><Name>".$s[$i]['name']."</Name>
           <DNS>".$s[$i]['ip']."</DNS><Lat>0</Lat><Long>0</Long><Usage>-1</Usage>
           <RankRequired>0</RankRequired></Server>";
}

So, I'm answering my own question (kinda). The comments helped me a lot. The thing is.. i should go to sleep because i am too tired for programming.

function ListServersXML($SERVER)
{
    $x = 0;
    $o = "";
    $s = sQuery($SERVER);
    while($x<$s['number'])
    {
        $o = $o . "<Server>
      <Name>".$s[$x]['name']."</Name>
      <DNS>".$s[$x]['ip']."</DNS>
    <Lat>0</Lat>
      <Long>0</Long>
      <Usage>-1</Usage>
      <RankRequired>0</RankRequired>
    </Server>";
        $x++;
    }
    return $o;
}

(btw this is my full function)

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