Foreach inside foreach

6

I need to execute a foreach within another foreach in PHP. But it returns me the following error:

  

Parse error: syntax error, unexpected T_FOREACH
referring to the line where the second foreach occurs

Here's part of the code:

$select = $bd -> prepare("SELECT * FROM umatabela ORDER BY id DESC");
$select -> execute();
$Fetch = $select -> fetchAll(PDO::FETCH_ASSOC);
$Conta = $select -> rowCount();

if ($Conta) {
  foreach ($Fetch as $postagem) {
    $oilUser = $postagem["sla"];

    $selectFoto = $bd->prepare("SELECT foto FROM outratabela WHERE cond='$oilUser' LIMIT 1");
    $selectFoto -> execute();
    $FetchFoto = $selectFoto -> fetchAll(PDO::FETCH_ASSOC);

    echo "
    <a href='#'>".foreach($FetchFoto as $autorFoto) {
    echo "<img src='".$autorFoto["foto"]."' alt='".$postagem["autor"]."' class='img-circulo'>";
    }."</a>
  }
}

How can I resolve this? Remember, I need to query in 2 different tables.

    
asked by anonymous 02.04.2015 / 20:29

2 answers

8

You can not concatenate a foreach with a string as you tried to do. You need to separate things:

echo "<a href='#'>";
foreach($FetchFoto as $autorFoto) {
    echo "<img src='".$autorFoto["foto"]."' alt='".$postagem["autor"]."' class='img-circulo'>";
}
echo "</a>";
    
02.04.2015 / 20:31
5

Can not concatenate a foreach as it should.

<?php
$select = $bd -> prepare("SELECT * FROM umatabela ORDER BY id DESC");
$select -> execute();
$Fetch = $select -> fetchAll(PDO::FETCH_ASSOC);
$Conta = $select -> rowCount();

if($Conta) {
    foreach($Fetch as $postagem) {
        $oilUser = $postagem["sla"];

        $selectFoto = $bd -> prepare("SELECT foto FROM outratabela WHERE cond = '$oilUser' LIMIT 1");
        $selectFoto -> execute();
        $FetchFoto = $selectFoto -> fetchAll(PDO::FETCH_ASSOC);

        $fotos = "";

        foreach ($FetchFoto as $autorFoto ) {
           $fotos .= "<img src='".$autorFoto["foto"]."' alt='".$postagem["autor"]."' class='img-circulo'>";
        }

        echo "
            <a href='#'>
                '.$fotos.'
            </a>";
    }
}

?>
    
02.04.2015 / 20:34