/    Sign up×
Community /Pin to ProfileBookmark

php in_array multi dimensional

Put simply, I’m looping through my database results and making an array of winners. 

The problem is with my in_array function I want to check if the master array as a nested array with the teamID of my winner or not. See below. Any ideas?  

When I check winner against  just $arr it adds a new item to for every winner, so a team may show 10 times 

$arr = array();while ($row = $result->fetch_assoc()) {            
if(in_array($row['Winner'], $arr['teamId'], true)){           

 } else {
    $arr[] = array('teamId' => $row['Winner'], 'Cnt' => 1);           
}  
to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@sibertJul 08.2023 — I’m looping through my database results...

I have found that looping through database results often (not always) can be done by a SQL query in one step. I have found that the WITH statement (CTE) is a very good way to move looping from your application code back to the SQL query. Faster and simpler.

I have not seen so many example that are using WITH in SQL queries. But basically there is two queries that works together. Create a LIST in WITH and then use this list to do further steps in the next query.

WITH list AS (SELECT * FROM team) //first query
SELECT sum(wins) FROM (SELECT * FROM list) //second query using the "list"
Copy linkTweet thisAlerts:
@buddyhelpAug 09.2023 — You can achieve this by using a flag to check whether a team ID exists in the $arr array. Here's the modified code snippet:

$arr = array();

while ($row = $result->fetch_assoc()) {
$found = false;

foreach ($arr as &$item) {
if ($item['teamId'] === $row['Winner']) {
$item['Cnt']++;
$found = true;
break;
}
}

if (!$found) {
$arr[] = array('teamId' => $row['Winner'], 'Cnt' => 1);
}
}


In this code, we iterate through the $arr array to check if the teamId already exists. If it does, we increment the Cnt value. If not, we add a new item to the array. This way, the team ID will not be added multiple times for the same winner. Let me know if you have questions. Thanks
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 10.12,
social: @webDeveloperHQ,
});

legal: ({
terms: of use,
privacy: policy
analytics: Fullres
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @aldoushuxley,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: @linalla,
tipped: article
amount: 1000 SATS,
)...