循环遍历数组并查看元素是否为空,如果不是空白则输出html

时间:2012-11-28 16:49:00

标签: php html

我有一个像这样的数组

Array
(
[0] => Array
    (
        [id] => 139
        [name] => Eithne Maun
        [contactNo] => 877692398
        [email] => eithne@yahoo.co.uk
        [address] => 
        [county] => Cork
        [country] => Ireland
        [sourceOfContact] => Phone
        [type] => Corporate
        [dateAdded] => 2012-11-26
        [companyName] => 
        [dateOfBirth] => 
    )

我想遍历数组中的每个元素,如果值不为空,则只显示下面的行

Number: <?php htmlout($contact[0]['contactNo']);?><br />
Email: <?php htmlout($contact[0]['email']);?><br />
Address: <?php htmlout($contact[0]['address']);?><br />
County: <?php htmlout($contact[0]['county']);?><br />
Country: <?php htmlout($contact[0]['country']);?><br />
Type of Contact: <?php htmlout($contact[0]['type']);?><br />
Company Name: <?php htmlout($contact[0]['companyName']);?><br />
Date of Birth: <?php htmlout($contact[0]['dateOfBirth']);?><br />

是否有一个我可以使用的循环函数?

3 个答案:

答案 0 :(得分:1)

$fields = array(
'Number' => 'contactNo',
'Email' => 'email',
'Address' => 'address',
'County' => 'county',
'Country' => 'country',
'Type of Contact' => 'type',
'Company Name' => 'companyName',
'Date of Birth' => 'dateOfBirth');

foreach ($fields as $key => $val)
{
    if (!empty($contact[0][$val]))
    {
        echo $key . ': ' . $contact[0][$val] . "<br />\n";
    }
}

答案 1 :(得分:0)

尝试

<?php
if(!empty($contact[0]['contactNo'])) { ?>
   Number: <?php htmlout($contact[0]['contactNo']);?><br />
<?php } ?>

答案 2 :(得分:0)

$record = array_filter($contact[0]);

然后遍历$ record中的每个条目,所有空条目都已被过滤掉

但是当使用像这样的

这样的array_filter时,注意0数值也被认为是空的