I'm developing an application in PHP 7 which has a list of users and their dietary requirements.
我正在开发一个PHP 7应用程序,它有一个用户列表和他们的饮食要求。
If any of the users have dietary requirements I need to show a link to a page that can display them; conversley if none of the users have such requirements then this isn't shown.
如果任何用户有饮食要求,我需要显示指向可以显示它们的页面的链接;如果没有用户有这样的要求,那么这不会显示。
My $users
array looks like this:
我的$ users数组看起来像这样:
[
[ 'name' => 'Andy', 'diet' => '' ],
[ 'name' => 'Bob', 'diet' => 'Vegeterian' ],
[ 'name' => 'John', 'diet' => '' ]
]
So in the above example, Bob has dietary requirements and the button needs to be shown.
所以在上面的例子中,Bob有饮食要求,需要显示按钮。
My plan to determine whether or not to show the button involves looping through the whole $users
array, and if it finds any 'diet'
array elements which aren't empty, it shows the button, e.g.
我决定是否显示按钮的计划涉及循环遍历整个$ users数组,如果它找到任何非“空”的'diet'数组元素,它会显示按钮,例如
$show_dietary_button = false;
foreach ($users as $user) {
if ($user['diet'] !== '') {
$show_dietary_button = true;
break;
}
}
if ($show_dietary_button) {
echo '<a href="#">Show Dietary Requirements</a>';
}
Is there an easier way to do this, i.e. a way to say do any of the array elements with a key 'diet' have data in them?
有没有更简单的方法来做到这一点,即一种方式来说,任何带有关键'饮食'的数组元素都有数据?
1 个解决方案
#1
2
You could just use a combination of array_filter
and array_column
to extract the column you want, then check if it's empty...
您可以使用array_filter和array_column的组合来提取所需的列,然后检查它是否为空...
if (!empty(array_filter(array_column($records, 'diet')))) {
$show_dietary_button = true;
}
Alternatively:
或者:
$show_dietary_button = !empty(array_filter(array_column($records, 'diet')));
#1
2
You could just use a combination of array_filter
and array_column
to extract the column you want, then check if it's empty...
您可以使用array_filter和array_column的组合来提取所需的列,然后检查它是否为空...
if (!empty(array_filter(array_column($records, 'diet')))) {
$show_dietary_button = true;
}
Alternatively:
或者:
$show_dietary_button = !empty(array_filter(array_column($records, 'diet')));