I have an array of database from a Wordpress page:
dev-user-20190424.php
<?php
$wb_users = array(
array(
"Username" => "Azmina",
"Level" => "form-5",
"School" => "KOLEJ D PATINGGI ABANG HJ ABDILLAH, SARAWAK",
"SchoolID" => 4522,
),
array(
"Username" => "Gudako",
"Level" => "form-5",
"School" => "KOLEJ D PATINGGI ABANG HJ ABDILLAH, SARAWAK",
"SchoolID" => 4522,
),
array(
"Username" => "Takatosaijo29",
"Level" => "form-5",
"School" => "SEKOLAH MENENGAH KEBANGSAAN BAHANG, SABAH",
"SchoolID" => 4210,
),
array(
"Username" => "Obon",
"Level" => "form-5",
"School" => "SEKOLAH MENENGAH KEBANGSAAN BAHANG, SABAH",
"SchoolID" => 4210,
),
array(
"Username" => "Rayana12",
"Level" => "form-5",
"School" => "SEKOLAH MENENGAH KEBANGSAAN BAHANG, SABAH",
"SchoolID" => 4210,
),
array(
"Username" => "kaiyuanbeh",
"Level" => "form-5",
"School" => "SEKOLAH MENENGAH KEBANGSAAN PERMATANG RAWA, PULAU PINANG",
"SchoolID" => 4250,
),
array(
"Username" => "Divyabharthi",
"Level" => "form-5",
"School" => "SEKOLAH MENENGAH KEBANGSAAN PETALING, WP KL",
"SchoolID" => 4244,
),
array(
"Username" => "blackchocolatecake",
"Level" => "form-4",
"School" => "SEKOLAH MENENGAH KEBANGSAAN POI LAM, PERAK",
"SchoolID" => 4375,
),
);
So what I am trying to achieve is to display the total number of users on another WordPress page by looping the array $wb-users and if SchoolID is matched current user school id variable, then count it. Then the total number of users will be displayed on the page.
I believe this is basically what you are looking for.
$schoolID = 4522;
$studentTotal = 0;
for ($i = 0; $i < count($wb_users); $i++) {
if ($wb_users[$i]['SchoolID'] === $schoolID) {
$studentTotal++;
}
}
You need to 1. Loop through the arrays within the main array. 2. Compare the 'SchoolID' key with your school ID variable. 3. Increment the counter when there is a match.
How about this with array_count_values
and array_column
?
$counts = array_count_values((array_column($wb_users, 'SchoolID')));
print_r($counts);
Output:
Array(
[4522] => 2
[4210] => 3
[4250] => 1
[4244] => 1
[4375] => 1
)
DEMO: https://3v4l.org/hCvq5