Last active
February 7, 2022 07:40
-
-
Save BataBoom/bb32d24ea7ac2ddab980fb0865bf27b7 to your computer and use it in GitHub Desktop.
Array_filter vs foreach/loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$matchU = array_values(array_column($winners, 'userID')); | |
$matchAmT = array_values(array_column($winners, 'amount')); | |
$count = count($matchU); | |
/* Method 1: for loop + foreach (identical result, preserves keys =[ )*/ | |
for ($n = 0; $n < $count; ++$n){ | |
if ($winners[$n]['userID'] === $matchU[$n]){ | |
$new[$matchU[$n]][$n] = array($matchAmT[$n]); | |
} | |
foreach ($winners as $key => $val){ | |
foreach ($val as $k => $v){ | |
if($k === 'userID' && $v === $matchU[$n]){ | |
$matches[$v][$n] = array($matchAmT[$n]); | |
} | |
} | |
} | |
/* Method 2: Array Filter, oddly if I remove array_values from Filter it preserves keys too but fiddling with that on method 1 doesnt result in diff outcomes */ | |
$winnerz[$n] = array_values(array_filter($winners, function($var) use ($yday, $matchU, $n) { | |
return ($var['start'] == $yday && $var['userID'] === $matchU[$n]); | |
})); | |
/* | |
RETURNS | |
Method 1: for loop + foreach (identical) | |
Array | |
( | |
[11d127b492bb] => Array | |
( | |
[0] => Array | |
( | |
[0] => 28 | |
) | |
[2] => Array | |
( | |
[0] => 74.454545454545 | |
) | |
) | |
[bataboom] => Array | |
( | |
[1] => Array | |
( | |
[0] => 78.272727272727 | |
) | |
) | |
) | |
Method 2: array_filter | |
[0] => Array | |
( | |
[0] => Array | |
( | |
[amount] => 28 | |
[userID] => user-2 | |
) | |
[1] => Array | |
( | |
[amount] => 74 | |
[userID] => user-2 | |
) | |
) | |
[1] => Array | |
( | |
[0] => Array | |
( | |
[amount] => 78 | |
[userID] => user-1 | |
) | |
) | |
Method two ftw.. | |
//finish chk balance from uid add up the sumzz and update | |
*/ | |
$total[] = array_column($winnerz[$n], 'amount'); | |
$uid[$n] = array_unique(array_column($winnerz[$n], 'userID')); | |
$sumz[] = array_sum($total[$n]); | |
$fb[] = $uid[$n][0]; | |
$bal[$fb[$n]] = fetchBalance("$fb[$n]"); | |
$updateBal[] = $sumz[$n] + $bal[$fb[$n]]; | |
$userKeyz = array_keys($bal); | |
updateBalance("$userKeyz[$n]", "$updateBal[$n]"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment