user6434562
user6434562

Reputation:

PHP mysql array_diff doesn't match all the fields

Old fields (cutoff)

| exceptions    |
+---------------+
| ryu,moderator |

New fields (accounts)

| username      |
+---------------+
| ben           |
+---------------+
| moderator     |
+---------------+
| john          |
+---------------+
| james         |
+---------------+
| ryu           |

I want to remove the duplicated fields but the code below didn't work (sample)

$expr_old = explode(',', $exceptions);
$expr_new = explode(',', $newfields);

echo implode(array_diff($expr_new, $expr_old), ',');

The full code

$query = "SELECT ACC.username AS username, SAL.income AS income, CDIR.exceptions AS except ";
$query .= "FROM accounts ACC ";
$query .= "LEFT JOIN info INF ON ACC.user_id = INF.iuid ";
$query .= "LEFT JOIN sales SAL ON ACC.user_id = SAL.suid ";
$query .= "LEFT JOIN cutoff_direct CDIR ON ACC.username = CDIR.user";

$s = $sqlConnection->query($query);

while ($row = $s->fetch_assoc())
{
    $ss = $sqlConnection->query("SELECT username FROM accounts WHERE sponsor = '$row[username]'");

    $exceptions = '';

    while ($rrow = $ss->fetch_assoc())
    {
        $exceptions .= $rrow['username'] . ',';
    }

    $expr_old = explode(',', $row['except']);
    $expr_new = explode(',', $exceptions);

    echo implode(array_diff($expr_new, $expr_old), ',');
}

Output: the username ryu remains

My problem is that some duplicate users appears unexpectedly.

Upvotes: 1

Views: 121

Answers (1)

Paras Jain
Paras Jain

Reputation: 393

I executed the following code and the output was as expected.

$exceptions = 'ryu,moderator';
$newfields = 'ben,moderator,john,james,ryu';
$expr_old = explode(',', $exceptions);
$expr_new = explode(',', $newfields);
echo implode(array_diff($expr_new, $expr_old),',');

Output :-

ben,john,james

Do check that the strings you are exploding do not contain any spaces. Words should be separated only by commas.

Upvotes: 2

Related Questions