Some Background
I have 2 arrays with the following information:
$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']
]
and
$y = [
'A' => [
'hasVIPmember' => false,
'slots' = [] //X elements will be placed here
]
'B' => [
'hasVIPmember' => false,
'slots' = [] //X elements will be placed here
]
The goal is to place each of the elements in $x into $y with only one VIP member. I have a method to place the VIP members and then one to place everyone else. The information in $x is obtained from a database. The '1' in VIP means true.
The Problem
The problem I am having is outlined in the comments in the code below.
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;
}
}
}
}
So the problem is, as you can see from the comments, when I perform if(!($y[$z['ykey']]['hasVIPmember'])){...} I only see the elements with the name "Fred" and, consequently, Fred is placed in both A and B.
The Question
Why is the list of items that are iterated through narrowed further in the final if statement? Is there any way to correct this behavior?

hasVIPmemberinside the loop, so even after you add a vipmember, you'll just keep adding more vip members,b ecause you never reset the flag to say one was added previously.