Monday, 27 August 2018

PHP - Compare two multidimensional arrays and add to a table accordingly


Today I'm having a bit of trouble figuring out a few things in PHP. As I normally do have the tendency to ramble a bit, I will try to keep my question short but concise. Here's what I'm trying to do.


Array #1 is a multidimensional array containing the results from MySQL query done against a user table in the database. It would look as such:
Array ( [0] => Array ( [id] => 79 [firstname] => John [lastname] => Doe [province] => Province [email] => someemail@gmail.com [primaryphone] => 123-456-7890 ) [1] => Array ( [id] => 113 [firstname] => Jane [lastname] => Doe [province] => Province [email] => email@gmail.com [primaryphone] => 123-456-7890 ) )

Array #2 is another multidimensional array containing the results from a MySQL query done against a membership table in the database that contains the id of the user that is associated with the current group. It looks as follows:
 Array ( [0] => Array ( [userid] => 79 ) [1] => Array ( [userid] => 115 ) [2] => Array ( [userid] => 124 ) )

What I am trying to do, is for every user returned in array #1, look for a value in array #2 under [userid] that matches the value [id] in array #1. If a match is found for each user, append the key and value [ismember] => 1 for that user in array #1 - if there is not a match, then append the pair [ismember] => 0 to array #1.
I feel that this should be a very simple process, and I'm probably just missing something that is elementary... But I've been going at it for a while now and haven't made much progress. Thank you all for your time and help.
== EDIT == The first array is generated by the following MySQL Query:
$query = "
    SELECT
        id,
        firstname,
        lastname,
        province,
        email,
        primaryphone
    FROM userstable
";
try
{
    $stmt = $db->prepare($query);
    $stmt->execute();
}
catch(PDOException $ex)
{
    die("Failed to run query: " . $ex->getMessage());
}
$allusersdetails = $stmt->fetchAll();

The second array is generated by the query:
$query = "
    SELECT
        userid
    FROM membershipstable
    WHERE templateid = :currenttemplateid
";
try
{
    $stmt = $db->prepare($query);
    $stmt->bindParam(':currenttemplateid', $currenttemplateid);
    $stmt->execute();
}
catch(PDOException $ex)
{
    die("Failed to run query: " . $ex->getMessage());
}
$templateusers = $stmt->fetchAll();

You can replace the 2 queries with one query like this:
$query = "
    SELECT
        u.id,
        u.firstname,
        u.lastname,
        u.province,
        u.email,
        u.primaryphone,
        (CASE WHEN m.userid IS NULL THEN 0 ELSE 1 END) AS ismember
    FROM userstable AS u
    LEFT JOIN membershipstable AS m ON
      m.templateid = :currenttemplateid AND
      u.id = m.userid
";
try
{
    $stmt = $db->prepare($query);
    $stmt->bindParam(':currenttemplateid', $currenttemplateid);
    $stmt->execute();
}
catch(PDOException $ex)
{
    die("Failed to run query: " . $ex->getMessage());
}
$allusersdetails = $stmt->fetchAll();

This will still pull all users, whether they are members or not but, it will add ismemberas column.
(the AS x part of userstable AS u and membershipstable AS m just assigns the letter as an alias of the table for the duration of the SELECT. Basically, it mostly helps you save on typing but also lets you JOIN on tables with columns of the same name.)
Welcome to the wonderful world of Structured Query Languages :D
EDIT And just in case someone comes here trying to do exactly what the question title is asking for but doesn't happen to be querying the database but does have a arrays in the exact format that the OP had:
<?php
$array =
    Array ( 0 => Array ( 'id' => '79','firstname' => 'John','lastname' => 'Doe','province' => 'Province','email' => 'someemail@gmail.com','primaryphone' => '123-456-7890',), 1 => Array ( 'id' => '113','firstname' => 'Jane','lastname' => 'Doe','province' => 'Province','email' => 'email@gmail.com','primaryphone' => '123-456-7890',) )
;
$array2 =
     Array ( 0 => Array ( 'userid' => '79'), 1 => Array ( 'userid' => '115'), 2 => Array ( 'userid' => '124') );

foreach($array as $key => $userInfo) {
    $isMember = 0;
    foreach($array2 as $user) {
        if($userInfo['id'] == $user['userid']) {
            $isMember = 1;
            break;
        }
    }
    $array[$key]['ismember'] = $isMember;
}

0 comments:

Post a Comment