1

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] => [email protected] [primaryphone] => 123-456-7890 ) [1] => Array ( [id] => 113 [firstname] => Jane [lastname] => Doe [province] => Province [email] => [email protected] [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();
6
  • you will need 2 for loops for array #1 and array #2 to match. Commented Jun 29, 2016 at 4:40
  • It sounds like you could do this with one MySQL query. Are you only using the 2nd array for this purpose? Commented Jun 29, 2016 at 4:40
  • So the two arrays come from different tables. One table is the user's information table, and the other table stores the association between the user's id and any group that they are associated with. Right now I am using one query to pull the user's info from the first array, and a second query to return their association with the current group. Commented Jun 29, 2016 at 4:46
  • @JohnDoe do you mind editing the 2 queries into the question? i'm sure i can help you work them into a single query. Commented Jun 29, 2016 at 4:51
  • 1
    @johndoe and I have to say, the formatting on the code is good and and you check for errors on your sql queries so, looks good to me! Commented Jun 29, 2016 at 14:39

2 Answers 2

1

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 ismember as 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' => '[email protected]','primaryphone' => '123-456-7890',), 1 => Array ( 'id' => '113','firstname' => 'Jane','lastname' => 'Doe','province' => 'Province','email' => '[email protected]','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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Works like a charm - as such, I'm convinced that you are either a magician or a deity of some sort... This mere mortal extends his most sincere gratitude and fidelity, my lord. XD
@JohnDoe lol, you flatter me;) but seriously, SQL is neither magic nor divine power! the evidence is that even i can learn it. read all you can about it! Never let yourself think "it would be cool if SQL/PHP/javascript could do this thing but it seems i'm have to use this big nasty code". There probably is some built-in way, or someone else has already found a nicer way of doing it. Always look around for a solution. Just don't spend too long looking either :D Good luck out there and happy programming!
0

Try this,

$firstArray = //your first array
$secondArray = // your second array
foreach($firstArray as $fa) {
    $id = $fa['id'];
}
foreach($secondArray as $sa) {
    $userId = $sa['userid'];
}
if($id === $userID) {
    $firstArray['ismember'] = 1;
} else {
    $firstArray['ismember'] = 0;
}

4 Comments

This outputs: ` Array ( [9] => Array ( [id] => 131 [firstname] => Jane [lastname] => Doe [province] => Province [email] => [email protected] [primaryphone] => 012-345-6789 ) [10] => Array ( [id] => 132 [firstname] => John [lastname] => Doe [province] => Province [email] => [email protected] [primaryphone] => 012-345-6789 ) [isnumber] => 0 )'` So it looks like the if statement is appending [isnumber] for the entire array that is one level up from the individual users...
So what do you exactly want? @JohnDoe
this code just compares the last 'id' from the first array to the last 'userid' from the second array
@Terminus you are right. This was the solution of first asked question. You answered like a boss, so I have no rights to regret you. "I have failed this question" ;) :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.