Foreach inside of foreach

Asked

Viewed 5,494 times

6

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

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

Follows 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 solve this? Remembering that, I need to make the queries in 2 different tables.

2 answers

9


You can’t grant a foreach with a string like 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>";

5

Can’t concatenate a foreach goes 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>";
    }
}

?>
  • 1

    Just so I understand, what is the difference between this solution and @bfavaretto’s?

  • The difference is only by the way of doing things I keep all the images of the foreach in the variable $fotos and then I call the variable $fotos to list them and only one way that clears the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.