php nested while loop in smarty using foreach

77 views Asked by At

I have the following PHP code.

$stmt = $pdo->prepare("SELECT * FROM memberships WHERE mb_status = 'enabled'");
$stmt-> execute();

$mbData = array();
while($f = $stmt->fetch()){
  $mbData[] = $f;
  $mbsId = $f['mb_id'];

  $stmtUpg = $pdo->prepare("SELECT * FROM upgrade_validities WHERE upval_membership = :mbs");
  $stmtUpg-> bindValue(':mbs', $mbsId);
  $stmtUpg-> execute();

  $upgVal = array();
  while($uf = $stmtUpg->fetch()){
    $upgVal[] = $uf;
  }
}
$smarty->assign('mbData', $mbData);
$smarty->assign('upgVal', $upgVal);

Smarty code using foreach

{foreach from=$mbData key=k item=b}
  {$b.mb_name}
  <!-- Listing Item -->
  {foreach from=$upgVal key=k item=a}
      <h3>Member Id: {$a.upval_id}</h3> // doesn't get displayed
  {/foreach}
  <!-- Listing Item / End -->
{/foreach}

Here, the Member Id in the nested foreach loop isn't getting displayed. I don't know what is the error I am making.

1

There are 1 answers

1
r_a_f On BEST ANSWER

PHP:

$stmt = $pdo->prepare("SELECT * FROM memberships WHERE mb_status = 'enabled'");
$stmt-> execute();

$mbData = array();
while($f = $stmt->fetch()){
  $mbData[] = $f;
  $mbsId = $f['mb_id'];

  $stmtUpg = $pdo->prepare("SELECT * FROM upgrade_validities WHERE upval_membership = :mbs");
  $stmtUpg-> bindValue(':mbs', $mbsId);
  $stmtUpg-> execute();

  // change begin
  $upgValTemp = array();
  while($uf = $stmtUpg->fetch()){
    $upgValTemp[] = $uf;
  }
  $upgVal[$mbsId] = $upgValTemp;

}
$smarty->assign('mbData', $mbData);
$smarty->assign('upgVal', $upgVal);

SMARTY:

{foreach from=$mbData key=k item=b}
  {$b.mb_name}
  <!-- Listing Item -->
  {foreach from=$upgVal[$b.mb_id] key=k item=a} {* changed here *}
      <h3>Member Id: {$a.upval_id}</h3>
  {/foreach}
  <!-- Listing Item / End -->
{/foreach}