Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php echo user's info only when elements are in common from sql

Tags:

sql

database

php

I'm trying to make all elements from the classlist to display only when they are in common with me and person b. for example if I have classes in position 1,2,5, and I'm on person b's profile who is in class 9,1,8,17,3, It would display ONLY 1 since they both have 1 in their classlist


(source: goawaymom.com)

I've tried a few things like exploding the classlist and giving everything their own variable... Nothing seems to work and I am over complicating everything i try. Does anyone know any simple ways to do this?

<?php
if ($_SESSION['classlist'] == $user_info['classlist']) {
echo ($user_info['classlist']);

} else {
    echo 'No Common Classes';
}
?>

The above code only displays the classlist when the order of the classlist of person a and b have the same classes in the same order.

like image 632
ramr Avatar asked May 23 '26 18:05

ramr


1 Answers

array_intersect

For example:

// fetch your results from the database
$myclasses = explode(',', $myrow['classlist']);
$theirclasses = explode(',', $theirrow['classlist']);

$common_classes = array_intersect($myclasses, $theirclasses);

Or in your case: (assuming that both $_SESSION['classlist'] and $user_info['classlist'] are strings containing comma separated numbers: '1,2,3,4,5')

$myclasses = explode(',', $_SESSION['classlist']);
$theirclasses = explode(',', $user_info['classlist']);
$common_classes = array_intersect($myclasses, $theirclasses);

if (count($common_classes) > 0)
{
    echo '<p>You have the following classes in common.</p>';
    echo '<ul>';
    foreach ($common_classes as $class)
    {
        echo '<li>' . $class . '</li>';
    }
    echo '</ul>';
}
else
{
    echo '<p>Billy no mates :(</p>';
}
like image 190
Dale Avatar answered May 26 '26 07:05

Dale