使用in_array()检查PHP数组中的值; [重复]

时间:2022-07-26 12:20:00

Possible Duplicate:
Implode array with “, ” and add “and ” before last item

可能重复:带有“,”的内爆数组,并在最后一项之前添加“和”

I'm customising a WordPress theme and I have created some checkboxes in the user profile page in the admin, 3 to be exact. When a user checks each box the value of that box is saved in an array calle $goals when they save their profile. This all works great.

我正在自定义一个WordPress主题,我在管理员的用户个人资料页面中创建了一些复选框,确切地说是3。当用户检查每个框时,该框的值将在保存其配置文件时保存在数组calle $ targets中。一切都很好。

On a template page I'm doing some tests on how to display certain content based on what goals the user has selected so I have created the following code which checks whether the array contains each value on it's own and then combinations of goals together and then echos specific content based on those selections. It works just fine but I feel the code is bloated and could be streamlined. This is something I'm always looking to do with my code. I would really appreciate your thoughts on how I can achieve the same results with less code. Thanks.

在模板页面上,我正在根据用户选择的目标对如何显示某些内容进行一些测试,因此我创建了以下代码,用于检查数组是否包含自己的每个值,然后将目标组合在一起然后基于这些选择的回声特定内容。它工作正常,但我觉得代码臃肿,可以简化。这是我一直希望用我的代码做的事情。我非常感谢您对如何用更少的代码实现相同结果的想法。谢谢。

$goals = get_user_meta( $userID, 'goals', $single );

if (in_array('Weight Loss', $goals, true) && !in_array('Improve Fitness', $goals, true) && !in_array('Improve Health', $goals, true)) {
    echo 'Weight Loss';
} elseif (in_array('Improve Fitness', $goals, true) && !in_array('Weight Loss', $goals, true) && !in_array('Improve Health', $goals, true)) {
    echo 'Improve Fitness';
} elseif (in_array('Improve Health', $goals, true) && !in_array('Improve Fitness', $goals, true) && !in_array('Weight Loss', $goals, true)) {
    echo 'Improve Health';
} elseif (in_array('Weight Loss', $goals, true) && in_array('Improve Fitness', $goals, true) && !in_array('Improve Health', $goals, true)) {
    echo 'Weight Loss and Improve Fitness';
} elseif (in_array('Weight Loss', $goals, true) && !in_array('Improve Fitness', $goals, true) && in_array('Improve Health', $goals, true)) {
    echo 'Weight Loss and Improve Health';
} elseif (!in_array('Weight Loss', $goals, true) && in_array('Improve Fitness', $goals, true) && in_array('Improve Health', $goals, true)) {
    echo 'Improve Fitness and Improve Health';
} elseif (in_array('Weight Loss', $goals, true) && in_array('Improve Fitness', $goals, true) && in_array('Improve Health', $goals, true)) {
    echo 'Weight Loss, Improve Fitness and Improve Health';
} else {
    echo 'Nothing set';
}

2 个解决方案

#1


2  

To represent the list of goals in a human readable form:

以人类可读的形式表示目标列表:

if (count($goals) > 1) {
    echo join(', ', array_slice($goals, 0, -1)) . ' and ' . end($goals);
} elseif ($goals) {
    echo $goals[0];
} else {
    echo "Nothing set";
}

Depending on how many items you have, the code will return either "X" / "X and Y" / "X, Y and Z".

根据您拥有的项目数量,代码将返回“X”/“X和Y”/“X,Y和Z”。

In the case of more than one item, it does the following:

如果有多个项目,则执行以下操作:

  1. Take the items up to but not including the last item - using array_slice() and put a comma in between them - using join().
  2. 获取项目但不包括最后一项 - 使用array_slice()并在它们之间加一个逗号 - 使用join()。

  3. Add the word " and " and the value of the last item.
  4. 添加单词“和”以及最后一项的值。

To narrow down the $goals array to just those items you mentioned:

要将$ goals数组缩小到您提到的那些项目:

$goals = array_intersect(array('Weight Loss', 'Improve Fitness', 'Improve Health'), $goals);

It strips out all values except the ones you're interested in, in your case just three of them. Depending on your situation, you may not need this code though.

除了您感兴趣的值之外,它会删除所有值,在您的情况下只有三个值。根据您的具体情况,您可能不需要此代码。

#2


0  

If you do not want to simply concatenate the strings as your example suggests, the more streamlined version of that code would be something like this:

如果您不想像示例所示简单地连接字符串,那么该代码的简化版本将更像这样:

sort($goals);

switch ($goals) {
    case array('Weight Loss') :
        ...
        break;

    case array('Improve Fitness', 'Weight Loss') :
        ...
        break;

    ...
}

The important thing here being that the elements in both arrays are in the same order, therefore the initial sort and the comparison elements being ordered alphabetically.

这里重要的是两个数组中的元素的顺序相同,因此初始排序和比较元素按字母顺序排序。

Having said that, there's got to be a better way of handling this than handling all possible permutations, since that goes up exponentially as you add more options. You should usually loop over the collection of goals, for each goal do something, then output some aggregate value:

话虽如此,必须有一个更好的方法来处理这个问题,而不是处理所有可能的排列,因为当你添加更多选项时,它会呈指数级增长。你通常应该遍历目标集合,为每个目标做一些事情,然后输出一些聚合值:

$output = array();

foreach ($goals as $goal) {
    switch ($goal) {
        case 'Weight Loss' :
            $output[] = 'I want to lose weight.';
            break;

        case 'Improve Fitness' :
            $output[] = ...
            break;

        ...
    }
}

echo join("\n", $output);

With a really sensible OOP based structure, where each goal is defined as an individual object, this could look even more like:

有了一个非常明智的基于OOP的结构,每个目标被定义为一个单独的对象,这看起来更像是:

$output = array();

foreach ($goals as $goal) {
    $output[] = $goal->objectiveDescription();
}

echo join("\n", $output);

In other words, the way you're approaching the problem is insufficient. It's hard to suggest something without knowing what you're actually trying to do though.

换句话说,你接近问题的方式是不够的。虽然不知道你真正想要做什么,但很难提出一些建议。

#1


2  

To represent the list of goals in a human readable form:

以人类可读的形式表示目标列表:

if (count($goals) > 1) {
    echo join(', ', array_slice($goals, 0, -1)) . ' and ' . end($goals);
} elseif ($goals) {
    echo $goals[0];
} else {
    echo "Nothing set";
}

Depending on how many items you have, the code will return either "X" / "X and Y" / "X, Y and Z".

根据您拥有的项目数量,代码将返回“X”/“X和Y”/“X,Y和Z”。

In the case of more than one item, it does the following:

如果有多个项目,则执行以下操作:

  1. Take the items up to but not including the last item - using array_slice() and put a comma in between them - using join().
  2. 获取项目但不包括最后一项 - 使用array_slice()并在它们之间加一个逗号 - 使用join()。

  3. Add the word " and " and the value of the last item.
  4. 添加单词“和”以及最后一项的值。

To narrow down the $goals array to just those items you mentioned:

要将$ goals数组缩小到您提到的那些项目:

$goals = array_intersect(array('Weight Loss', 'Improve Fitness', 'Improve Health'), $goals);

It strips out all values except the ones you're interested in, in your case just three of them. Depending on your situation, you may not need this code though.

除了您感兴趣的值之外,它会删除所有值,在您的情况下只有三个值。根据您的具体情况,您可能不需要此代码。

#2


0  

If you do not want to simply concatenate the strings as your example suggests, the more streamlined version of that code would be something like this:

如果您不想像示例所示简单地连接字符串,那么该代码的简化版本将更像这样:

sort($goals);

switch ($goals) {
    case array('Weight Loss') :
        ...
        break;

    case array('Improve Fitness', 'Weight Loss') :
        ...
        break;

    ...
}

The important thing here being that the elements in both arrays are in the same order, therefore the initial sort and the comparison elements being ordered alphabetically.

这里重要的是两个数组中的元素的顺序相同,因此初始排序和比较元素按字母顺序排序。

Having said that, there's got to be a better way of handling this than handling all possible permutations, since that goes up exponentially as you add more options. You should usually loop over the collection of goals, for each goal do something, then output some aggregate value:

话虽如此,必须有一个更好的方法来处理这个问题,而不是处理所有可能的排列,因为当你添加更多选项时,它会呈指数级增长。你通常应该遍历目标集合,为每个目标做一些事情,然后输出一些聚合值:

$output = array();

foreach ($goals as $goal) {
    switch ($goal) {
        case 'Weight Loss' :
            $output[] = 'I want to lose weight.';
            break;

        case 'Improve Fitness' :
            $output[] = ...
            break;

        ...
    }
}

echo join("\n", $output);

With a really sensible OOP based structure, where each goal is defined as an individual object, this could look even more like:

有了一个非常明智的基于OOP的结构,每个目标被定义为一个单独的对象,这看起来更像是:

$output = array();

foreach ($goals as $goal) {
    $output[] = $goal->objectiveDescription();
}

echo join("\n", $output);

In other words, the way you're approaching the problem is insufficient. It's hard to suggest something without knowing what you're actually trying to do though.

换句话说,你接近问题的方式是不够的。虽然不知道你真正想要做什么,但很难提出一些建议。