简体   繁体   中英

IF ELSEIF fo array inside While loop PHP

I've get the value inside literal tag in this xml:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="/xml-to-html.xsl"?>
<sparql xmlns="http://www.w3.org/2005/sparql-results#">
  <head>
    <variable name="Kategori"/>
  </head>
  <results>
    <result>
      <binding name="Kategori">
        <literal datatype="http://www.w3.org/2001/XMLSchema#string">Gerak Kasar</literal>
      </binding>
    </result>
    <result>
      <binding name="Kategori">
        <literal datatype="http://www.w3.org/2001/XMLSchema#string">Gerak Halus</literal>
      </binding>
    </result>
  </results>
</sparql>

using this code:

$x = 0;
$kategori = array();
while ($x < count($hasilcek->results->result)) {
$kategori[$x]= $hasilcek->results->result[$x]->binding->literal;
$x++; }

But when I try to get the result by IF ELSEIF inside WHILE using this code:

$x = $x-1;
while ($x > -1){
if ($kategori[$x] = 'Gerak Kasar') {echo "Gerak Kasar";}
elseif ($kategori[$x] = 'Gerak Halus') {echo "Gerak Halus";}
else {echo "tidak ada";}
$x--;}

exactly the result should be:

Gerak Kasar Gerak Halus

but why i get :

Gerak KasarGerak Kasar

I think there is something wrong when I do IF selection for $kategori[] inside the WHILE. Can anyone explain? Thanks.

instead of comparison operator your are using assignment operator.

if ($kategori[$x] = 'Gerak Kasar') {echo "Gerak Kasar";}
elseif ($kategori[$x] = 'Gerak Halus') {echo "Gerak Halus";}

So change it to

 if ($kategori[$x] == 'Gerak Kasar') {echo "Gerak Kasar";}
 elseif ($kategori[$x] == 'Gerak Halus') {echo "Gerak Halus";}

Because when if ($kategori[$x] = 'Gerak Kasar') is executed $kategori[$x] become Gerak Kasar always. That is why you get the same result again.

Selamat Pagi. :)

Try this :

$x = $x-1;
while ($x > -1){
if ($kategori[$x] == 'Gerak Kasar') {echo " Gerak Kasar ";}
elseif ($kategori[$x] == 'Gerak Halus') {echo " Gerak Halus ";}
else {echo "tidak ada";}
$x--;}

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