0

I am working on a reporting dashboard for our company intranet site. The function below is selecting all of the jobs and suffix from a table. I'm using PDO fetchall to retrieve my results. the array looks like:

Array
( 
    [0] => Array 
    ( 
        [JOB] => 197182 
        [SUFFIX] => 002 
    ) 
    [1] => Array 
    ( 
        [JOB] => M03001 
        [SUFFIX] => 001 
    ) 
    [2] => Array 
    ( 
        [JOB] => 197182 
        [SUFFIX] => 002 
    )
)

In this case, the dashboard should have 2 rows, 1 for each job (excluding the duplicate) however how can I search through this array and have it only return a row count of 2 instead of 3? Since there is a duplicate job and suffix I don't want to create a third row with the same job-suffix so it should only be two rows.

function row_count() 
{
    $conn = new PDO('odbc:GLOBALTST');
    $result = $conn->prepare('SELECT JOB, SUFFIX FROM JOBS_IN_PROCESS_G');
    $result->execute();
    $row = $result->fetchall(PDO::FETCH_ASSOC);
    global $count;
    $count = count($row);\\ if I print this out I get 3
}
Remy
  • 777
  • 2
  • 8
  • 15
  • `array_unique()` ? – Jaquarh Feb 04 '21 at 16:39
  • 1
    @Jaquarh per the php documentation on array_unique this function isn't intended to work on multidimensional arrays. –  Feb 04 '21 at 16:43
  • 1
    In this case a simple loop and unset tracked duplicates would suffice. But relying on your data layer to take care of it is probably nicer, if it might be a recurring theme you could also create a view for it. – Remy Feb 04 '21 at 16:47
  • Why aren't you performing the count in SQL? – Dharman Feb 04 '21 at 17:02

2 Answers2

1

You can fix that on your query side by selecting DISTINCT rows of JOB and SUFFIX column like below,

$result = $conn->prepare('SELECT DISTINCT JOB, SUFFIX FROM JOBS_IN_PROCESS_G');

OR if you want on PHP side after selecting rows from table then check this example , But I prefer first one as it is better to get only what you need from DB table.

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • 1
    I second the notion that it should be done on the DB end. A good rule of thumb is don't ask for more than you need. – El_Vanja Feb 04 '21 at 17:05
0

You can also do this in PHP by utilising the array_column. See it working over at 3v4l.org.

$unDuplicated = array_combine(array_column(($rows = $result->fetchall(PDO::FETCH_ASSOC)), 'SUFFIX'), $rows);

If you want to keep the order, use array_reverse.

Jaquarh
  • 6,493
  • 7
  • 34
  • 86