简体   繁体   English

无法从Foreach循环中提取变量

[英]Can't extract variables from Foreach loop

I have an existing array that I want to extract the first name and last name out separately from a single full name field from and put each into their own variable. 我有一个现有的数组,我想从一个全名字段中单独提取名字和姓氏,并将每个名称和数字放入自己的变量中。 I've got the extraction to work the way I need, but I can't seem to retrieve the data once I'm out of the 'foreach' loop. 我已经将提取工作按照我需要的方式工作,但是一旦我离开'foreach'循环,我似乎无法检索数据。

My array is this.. 我的阵列是这个..

Array
(
    [0] => 2
    [1] => dduck
    [2] => Donald Duck
    [3] => donald@domain.com
)

When I run the foreach loop (below) the echo works. 当我运行foreach循环(下面)时,回声起作用。 But if I echo the $firstName and $lastName outside of the loop, nothing is displayed.... 但是,如果我在循环之外回显$ firstName和$ lastName,则不显示任何内容....

This displays first and last name 这会显示名字和姓氏

foreach ($t_result as $name)
{
    preg_match('#^(\w+\.)?\s*([\'\’\w]+)\s+([\'\’\w]+)\s*(\w+\.?)?$#', $name, $results);
    $firstName = $results[2];
    $lastname = $results[3];
    echo $firstName . " " . $lastname;
}

This displays nothing 这没什么

foreach ($t_result as $name)
{
    preg_match('#^(\w+\.)?\s*([\'\’\w]+)\s+([\'\’\w]+)\s*(\w+\.?)?$#', $name, $results);
    $firstName = $results[2];
    $lastname = $results[3];
}
echo $firstName . " " . $lastname;

Any ideas? 有任何想法吗?

You are not checking whether or not there is a match on your regex so for the array elements that do not match you are assigning $firstName and $lastname to undefined indexes. 您没有检查正则表达式是否匹配,因此对于与您不匹配的数组元素,您将$firstName$lastname分配给未定义的索引。

The example array will not match on element [3] so those variables are more or less empty at the end of the loop making your echo outside of the loop not display anything. 示例数组在元素[3]上不匹配,因此这些变量在循环结束时或多或少为空,使得循环外部的回显不显示任何内容。

You can try something like the following (wrapping the preg_match in an if statement): 您可以尝试以下内容(将preg_match包装在if语句中):

foreach ($t_result as $name)
{
    if (preg_match("#^(\w+\.)?\s*(['\’\w]+)\s+(['\’\w]+)\s*(\w+\.?)?$#", $name, $results)) {
       $firstName = $results[2];
       $lastname = $results[3];
    }
}
echo $firstName . " " . $lastname;

You need to wrap the variables you're tring to return in an 'if' statement, otherwise the values are overwritten by subsequent loops: 您需要在“if”语句中包含要返回的变量,否则后续循环会覆盖这些值:

$t_result = array(
    0 => 2,
    1 => 'dduck',
    2 => 'Donald Duck',
    3 => 'donald@domain.com',
);

foreach ( $t_result as $name ) {
    if ( preg_match( '#^(\w+\.)?\s*([\'\’\w]+)\s+([\'\’\w]+)\s*(\w+\.?)?$#', $name, $results ) ) {
        $firstName = $results[2];
        $lastname = $results[3];
    }
}

echo $firstName . " " . $lastname;

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

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