Fahmi Fahmi - 4 months ago 17
PHP Question

Skip foreach if same value as database

First of all sorry for my bad english. I would like to ask you how to skip foreach loop from xml if a value is in the database.

Here's the foreach code from the xml:

$xml=simplexml_load_file("http://localhost:80/ijarah/webservice/show_data_mobil.xml") or die("Error: Cannot create object");
foreach($xml->children() as $mobil){
echo $mobil->nama;
echo "<br>";
}


And the result :

Toyota Avanza 2012 B 4230 XCM
Toyota Innova 2004 B 12349 DAC
Honda Carrens 2002 B 1408 N0H
Honda Supra X 2007 B 6754 NAC
Yamaha Vixion 2013 B 1564 TBR
Honda Supra 2002 B 8764 ZMN
Honda Supra Fit 2007 B 5533 KAC


This is my database's filter code

$getnas = $con->query("select * from transaksi_pembiayaan where STATUS='Belum Lunas'");
while ($row = $getnas->fetch_assoc()) {
$getBar = $con->query("select id_barang from pengajuan where id_nasabah='$row[id_nasabah]'");
while ($rows = $getBar->fetch_assoc()) {
$getBarang = $con->query("select nama_barang from barang where id_barang='$rows[id_barang]'");
while ($rok = $getBarang->fetch_assoc()) {
echo $rok['nama_barang'];
echo '<br>';
}
}
}


And the result :

Honda Carrens 2002 B 1408 N0H
Honda Supra X 2007 B 6754 NAC


So, how do I skip data foreach loop xml from database filter? In other words, this is the result I want based on xml and database filter.

Toyota Avanza 2012 B 4230 XCM
Toyota Innova 2004 B 12349 DAC
Honda Carrens 2002 B 1408 N0H <- Needs to be skipped
Honda Supra X 2007 B 6754 NAC <- This one too
Yamaha Vixion 2013 B 1564 TBR
Honda Supra 2002 B 8764 ZMN
Honda Supra Fit 2007 B 5533 KAC


How do I do this? Thank you.

Answer Source

Store your database filter output in an array:

$filterOutput=array();
$getnas = $con->query("select * from transaksi_pembiayaan where STATUS='Belum Lunas'");
while ($row = $getnas->fetch_assoc())
{
    $getBar = $con->query("select id_barang from pengajuan where id_nasabah='$row[id_nasabah]'");
    while ($rows = $getBar->fetch_assoc())
    {
        $getBarang = $con->query("select nama_barang from barang where id_barang='$rows[id_barang]'");
        while ($rok = $getBarang->fetch_assoc())
        {
//          echo $rok['nama_barang'];
//          echo '<br>';
            $filterOutput[]=$rok['nama_barang'];
        }
    }
}

Then use the filter output:

$xml=simplexml_load_file("http://localhost:80/ijarah/webservice/show_data_mobil.xml") or die("Error: Cannot create object");
foreach($xml->children() as $mobil)
{
    if (in_array($mobil->nama,$filterOutput))
    {
        continue;
    }
    echo $mobil->nama;
    echo "<br>";
}