0

这是建议的结果我是PHP的菜鸟,我想在每一行中使用foreach语句显示非空值,代码如下,非常感谢您的支持

<?php

       foreach ($customer['Stocks'] as $stock ) { ?>
       <tr>
          <td><?php echo $stock['stsymbol']?><td>
          <td><?php echo $stock['noshares']?><td>
          <td><?php echo $stock['purchaseprice']?><td>
          <td><?php echo $stock['datepurchased']?><td>
          <td><?php echo $stock['Original Value']; ?><td>
          <td><?php echo $stock['Current Price'];?><td>
          <td><?php echo $stock['Current Value']?><td>
<?php } // end foreach ?>
4

4 回答 4

1
<?php
    foreach ($customer['Stocks'] as $stock ) {
        if( ! empty($stock['stsymbol'])){ ?>
        <tr>
            <td><?php echo $stock['stsymbol']?><td>
            <td><?php echo $stock['noshares']?><td>
            <td><?php echo $stock['purchaseprice']?><td>
            <td><?php echo $stock['datepurchased']?><td>
            <td><?php echo $stock['Original Value']; ?><td>
            <td><?php echo $stock['Current Price'];?><td>
            <td><?php echo $stock['Current Value']?><td>
        </tr>
<?php
        } // end if
    } // end foreach ?>
于 2013-07-17T07:40:33.123 回答
0

使用三元运算符显示您的“null”值,否则为空字符串:

<?php
    foreach ($customer['Stocks'] as $stock ) { ?>
    <tr>
        <td><?php echo ($stock['stsymbol'] == NULL) ? $stock['stsymbol'] : ''; ?></td>
        <td><?php echo ($stock['noshares'] == NULL) ? $stock['noshares'] : ''; ?></td>
        <td><?php echo ($stock['purchaseprice'] == NULL) ? $stock['purchaseprice'] : ''; ?></td>
        <td><?php echo ($stock['datepurchased'] == NULL) ? $stock['datepurchased'] : ''; ?></td>
        <td><?php echo ($stock['Original Value'] == NULL) ? $stock['Original Value'] : ''; ?></td>
        <td><?php echo ($stock['Current Price'] == NULL) ? $stock['Current Price'] : ''; ?></td>
        <td><?php echo ($stock['Current Value'] == NULL) ? $stock['Current Value'] : ''; ?></td>
    </tr>
<?php } // end foreach ?>

希望你明白

于 2013-07-17T07:30:18.163 回答
0

您可以像这样遍历数组:

foreach($customer['stocks'] as $key => $value) {

    if(empty($value)) {

        $customer['stocks'][$key] = '-';


    }

}

使您的显示代码更具可读性:

foreach ($customer['Stocks'] as $stock ) {

    echo('<tr>
      <td>'.$stock['stsymbol'].'<td>
      <td>'.$stock['noshares'].'<td>
      <td>'.$stock['purchaseprice'].'<td>
      <td>'.$stock['datepurchased'].'<td>
      <td>'.$stock['Original Value'].'<td>
      <td>'.$stock['Current Price'].'<td>
      <td>'.$stock['Current Value'].'<td>
    </tr>');

}
于 2013-07-17T07:30:45.237 回答
-1
<td><?= strlen($stock['stsymbol'])!==0? $stock['stsymbol'] : '-' ?><td>

我用这个替换你的回声,这是简短的方法:

// These do the same:
<td><?php echo $something; ?></td>
<td><?= $something ?></td>

然后在回声中,我做了一个简短的 if/else(三元),它的工作原理如下:

if( strlen($var)===0 ){ echo 'true'; } else{ echo 'false'; }
echo strlen($var)===0 )? 'true' : 'false'; 
// (condition) ? (if true) : (if false);

而不是strlen($var)!==0, 你也可以做isset($var), 的$var===NULL

于 2013-07-17T07:24:25.977 回答