我在这里有一点问题:如果数据库表中有条目,我只想输出内容。现在我的代码看起来像这样:
foreach ($customers as $customer) {
if ($customer->CURRENT_ROWNAME != NULL) {
//output stuff e.g.
<p>ID: {{$customer->customer_id}}</p>
<p>E-Mail: {{$customer->email}}</p>
<p>Phone: {{$customer->phone}}</p>
<p>Mobile: {{$customer->mobile}}</p>
else {
//do not output stuff
}
}
我想我应该搜索输出当前字段名称的内容,以便它跳过空条目,例如,如果表中没有移动号码,则不输出。所以我的逻辑从一开始就存在缺陷。这导致我找到一个相当不美观的“解决方案”:
@foreach ($customers as $customer)
<h2>{{$customer->name}} | {{$customer->company}}</h2>
<div class="column-left">
<p>ID: {{$customer->customer_id}}</p>
<p>E-Mail: {{$customer->email}}</p>
<p>Phone: {{$customer->phone}}</p>
@if($customer->mobile != NULL)
<p>Mobile: {{$customer->mobile}}</p>
@else
@endif
</div>
@endforeach
所以这确实有效。但理论上,我需要手动对每个数据库条目执行此操作,我不完全确定,如果该字段可能为空白。
有更好的解决方案吗?
我想你可以使用array_filter
:
<?php
$data = array(
0 => array(
'name'=> '',
'company'=>'companyName',
'customer_id'=> 123456,
'phone'=> '11111',
),
1 => array(
'name'=> 'Tom',
'company'=>'',
'customer_id'=> 123457,
'phone'=> '11112',
),
2 => array(
'name'=> 'Daniel',
'company'=>'companyName',
'customer_id'=> '',
'phone'=> '11113',
),
3 => array(
'name'=> 'Bob',
'company'=>'companyName',
'customer_id'=> 123458,
'phone'=> '',
),
4 => array(
'name'=> 'Amy',
'company'=>'companyName',
'customer_id'=> '123456',
'phone'=> '11114',
),
);
$customers = array();
foreach ($data as $value) {
array_push($customers,array_filter( $value));
}
print_r($customers);
return $customers;
上面的例子将输出:
Array
(
[0] => Array
(
[company] => companyName
[customer_id] => 123456
[phone] => 11111
)
[1] => Array
(
[name] => Tom
[customer_id] => 123457
[phone] => 11112
)
[2] => Array
(
[name] => Daniel
[company] => companyName
[phone] => 11113
)
[3] => Array
(
[name] => Bob
[company] => companyName
[customer_id] => 123458
)
[4] => Array
(
[name] => Amy
[company] => companyName
[customer_id] => 123456
[phone] => 11114
)
)
在客户模型上,您可以将逻辑放在那里,例如;
public function hasMobile() {
if($this->mobile){
return '<p>Mobile: ' . $this->mobile . '</p>';
}
return null;
}
对于您想要显示/不显示的每个项目,然后在您的视图中,您可以每次引用,而不是在x个视图中使用if语句。如果你需要更新它,更新一个它们都会改变它也会很好
观点会是这样的;
{{ $customer->hasMobile() }}
最有可能是更好的方式,但这是我想要的选择。