简体   繁体   English

我的PHP foreach命令仅作用于数组的最后一项!

[英]My PHP foreach commands only act on the last item of the array!

I'm taking the input from a text field, turning each line into a value in an array, and then using a foreach loop to run a search and replace on each value. 我从文本字段获取输入,将每一行变成数组中的一个值,然后使用foreach循环运行搜索并替换每个值。 Code is as follows: 代码如下:

$countryinp = trim($_POST['country']);
$countryinp = explode("\n", $countryinp);
$countryinp = array_filter($countryinp, 'trim');
foreach($countryinp as $code)
{
$country = '';
if( $code == 'Afghanistan' ) $country = 'AF';
if( $code == 'Aland Islands' ) $country = 'AX';
if( $code == 'Albania' ) $country = 'AL';
if( $code == 'Algeria' ) $country = 'DZ';
...
if( $country == '') $country = $code;
echo "$country";
echo "<br />";
unset($code);
}

The code will loop and output a list of all the inputs, but it only sets $country to a two letter code for the last line of the input! 该代码将循环并输出所有输入的列表,但仅将$country设置$country输入最后一行的两个字母的代码! I'm going crazy, anyone seen this before? 我快疯了,以前有人看过吗?

Try something like this... 试试这样的东西...

foreach($countryinp as $code)
{
$code = trim($code);
    switch($code){
        case "Afganistan": $country = "AF"; break;
        case "Alanad Islands": $country = "AX"; break;
        default: $country = $code;
    }

    echo $country."<br />";
}

And make sure your data exists... 并确保您的数据存在...

What problem are you having exactly? 您到底有什么问题? You say that it only sets $country to a two-letter code for the last line, but is it printing out all of the codes before that? 您说它仅将$country设置为最后一行的两个字母的代码,但是它会在此之前打印出所有代码吗?

This should be obvious, but if you're only having problems with the value of $country after the loop finishes, then you should realize that the $country variable is overwritten on each iteration of the loop, and would therefore only hold the value from the last iteration when the loop finishes. 这应该很明显,但是如果循环结束后仅遇到$country的值问题,那么您应该意识到$country变量在循环的每次迭代中都将被覆盖,因此将仅保存来自循环结束时的最后一次迭代。

If the problem is that your loop isn't printing each code, then that sounds like it's a data problem, and you would need to show us the values in your array in order to determine the problem. 如果问题是您的循环没有打印每个代码,那么这听起来像是一个数据问题,您需要向我们显示数组中的值才能确定问题。

One possible data problem you may have is this line: 您可能遇到的一种数据问题是以下行:

$countryinp = array_filter($countryinp, 'trim');

I think your intent with this line is to apply the trim function to each element in the array, but that's not what array_filter does. 我认为这行的目的是将trim函数应用于数组中的每个元素,但这不是array_filter所做的。 The function of array_filter is to pass each element in an array to a callback function. array_filter的功能是将数组中的每个元素传递给回调函数。 That function examines the contents of the element, then returns true if the contents should be kept, or false if that element should be filtered out of the array. 该函数检查元素的内容,如果应保留内容,则返回true如果应从数组中滤除该元素,则返回false

When you pass trim to array_filter , the only thing that happens is that any array element which is empty, or only contains whitespace, will be removed. 当将trim传递给array_filter ,唯一发生的事情是将删除任何为空或仅包含空格的数组元素。 This is because after such elements are trimmed, they are empty. 这是因为修剪此类元素后,它们为空。 PHP interprets an empty string as false and removes it from the array. PHP将空字符串解释为false并将其从数组中删除。

This could cause issues with your if statements, because if $code contains, for example, "Afghanistan " (note the trailing space), then it wouldn't get caught by the if statement as the strings wouldn't match. 这可能会导致if语句出现问题,因为如果$code包含例如“ Afghanistan”(注意尾随空格),则它将不会被if语句捕获,因为字符串不匹配。

You would be much better off simply running the line $code = trim($code); 您只需运行$code = trim($code);行会更好$code = trim($code); at the beginning of your foreach loop. foreach循环的开始。

Also, your code is a little bit ugly to me. 另外,您的代码对我来说有点难看。 If you're just going to check the same variable over and over (ie repeated if ($code == 'Value') statements), then you should really be using a switch statement instead: 如果您要一遍又一遍地检查相同的变量(即重复执行if ($code == 'Value')语句),那么您实际上应该使用switch语句:

switch ($code) {
    case "Afghanistan":
        $country = 'AF';
        break;
    case "Aland Islands":
        $country ='AX';
        break;
    // repeat for other cases
    default:
        $country = $code;
}

You can too many logical issues with this piece of code 这段代码可能会导致太多逻辑问题

foreach($countryinp as $code) // #1
{
$country = ''; // #2
if( $code == 'Afghanistan' ) $country = 'AF'; // #3
if( $code == 'Aland Islands' ) $country = 'AX';
if( $code == 'Albania' ) $country = 'AL';
if( $code == 'Algeria' ) $country = 'DZ';
...
if( $country == '') $country = $code; #4
echo "$country";
echo "<br />";
unset($code); // #5
}
  1. $code is variable visible in foreach scope, assigned with value of next($countryinp) (pointer to next element in array) $ code是在foreach范围内可见的变量,分配有next($ countryinp)的值(指向数组中下一个元素的指针)

  2. $country is reset to '' (empty value) on each iteration (you are resetting $country value) $ country在每次迭代中都重置为''(空值)(您正在重置$ country值)

  3. $code == 'xxxx' - here you can use switch() statement, two benefits: 1) expression is evaluated only once then matched against 'case' and 2) maintainability (if you have to change something in your code... Better solution would be to simply have array with country name as key and country code as value, then you can directly access the country code like this $countryCodes[$countryName]; $ code =='xxxx'-在这里您可以使用switch()语句,有两个好处:1)仅对表达式求值一次,然后与'case'匹配; 2)可维护性(如果您必须在代码中进行某些更改...更好的解决方案是将国家名称作为键,将国家代码作为值,然后可以直接访问国家代码,例如$ countryCodes [$ countryName];。

  4. Here you assign current country $code to $country only if $country is empty but as mantioned in #2 you are resetting $country value on each iteraction 在这里,仅当$ country为空时,才将当前国家/地区的$ code分配给$ country,但是如#2所述,您每次迭代都要重置$ country的值

  5. Here you unset the value of $code and this is not necessary, $code is only visible inside foreach() and automatically unset when your code exists the foreach loop. 在这里,您可以取消设置$ code的值,这不是必需的,$ code仅在foreach()内部可见,并且当代码存在foreach循环时会自动取消设置。

Hope that helps. 希望能有所帮助。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM