一些背景

我有2个数组,其中包含以下信息:

$x = [
    ['name' => 'Fred', 'ykey' => 'A', 'rank' => '1', 'VIP' => '1'],
    ['name' => 'Fred', 'ykey' => 'B', 'rank' => '2', 'VIP' => '1'],
    ['name' => 'Joe', 'ykey' => 'A', 'rank' => '1', 'VIP' => '1'],
    ['name' => 'Joe', 'ykey' => 'B', 'rank' => '2', 'VIP' => '1'],
    ['name' => 'Frank', 'ykey' => 'A', 'rank' => '1', 'VIP' => '0'],
    ['name' => 'Frank', 'ykey' => 'B', 'rank' => '2', 'VIP' => '0']
]




$y = [
    'A' => [
        'hasVIPmember' => false,
        'slots' = [] //X elements will be placed here
    ]
    'B' => [
        'hasVIPmember' => false,
        'slots' = [] //X elements will be placed here
    ]


目标是仅由一个VIP成员将$x中的每个元素放入$y中。我有一种方法来放置VIP成员,然后再一种方法来放置其他所有人。 $x中的信息是从数据库中获得的。 VIP中的'1'表示true

问题

我在下面的代码的注释中概述了我遇到的问题。

for($i = 1; $i <= 2; $i++){
    foreach($x as $z){
        //all Xs are seen here (after all iterations complete)
        if($z['VIP'] == 1 && $z['rank'] == $i){
            //Only Fred and Joe elements of X are shown here. (after all iterations complete)
            if(!($y[$z['ykey']]['hasVIPmember'])){
                //Only 'Fred' elements are shown here. Why?(after all iterations complete)
                $y[$z['ykey']]['slots'][]= $z;
                $y[$z['ykey']]['hasVIPmember'] = true;
            }
        }
    }
}


因此,问题是,正如您从注释中看到的那样,当我执行if(!($y[$z['ykey']]['hasVIPmember'])){...}时,我只会看到名称为“ Fred”的元素,因此,Fred放置在A和B中。

问题

为什么最终if语句中迭代的项目列表会进一步缩小?有什么办法可以纠正这种行为?

最佳答案

当您运行迭代时,Fred在等级1和2上都是第一个。运行时,它会将Fred添加到$ y,然后跳过其余部分,因为此时$ y [hasVIPmember]为true。在使用某种计数器或密钥将Fred添加到任何$ y后,或者更改您的数据集之后,您需要找到一种方法使Fred从运行中无效。

$used = NULL;
for($i = 1; $i <= 2; $i++){
    foreach($x as $z){
        //all Xs are seen here (after all iterations complete)
        if($z['VIP'] == 1 && $z['rank'] == $i){
            //Only Fred and Joe elements of X are shown here. (after all iterations complete)
            if(!($y[$z['ykey']]['hasVIPmember'])){
                // looks for used
                if (!($z['name'] == $used)) {
                    $y[$z['ykey']]['slots'][]= $z;
                    $y[$z['ykey']]['hasVIPmember'] = true;
                    $used = $z['name']; //add Fred to the used name list
                }

            }
        }
    }
}

关于php - PHP-嵌套的foreach循环中的异常行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32404507/

10-10 08:06