1

I query a database in PHP which will get results like the following table. These are stored in an associative array.

Data returned from query

What I now want to be able to do is select only the records by a certain work_type and return the same type of associative array. For example "Part Time". Then I want to be able to sort these records according to whatever column I decide. How would I do this?

This is as far as I got...

$data = $_SESSION['results']; //the database query results

foreach($data as $key => $row)
{
    if(in_array($row['work_type'], array('Part Time')))
    {
        $type[$key] = $row['work_type'];
        $date_posted[$key] = $row['created_at'];
    }
}
array_multisort($type, SORT_ASC, $date_posted, SORT_ASC, $data);

This doesn't work because the $data array which I send to multi-sort is a now different size to the ones I created.

Magearlik
  • 523
  • 1
  • 6
  • 18
  • what is `array('Part Time')`?? – Alive to die - Anant Apr 24 '18 at 04:20
  • 1
    [array_filter](http://us3.php.net/manual/en/function.array-filter.php) would make a lot more sense than a foreach loop here to filter your results so you only have records of a certain type. It would make a lot more sense to add a WHERE clause to your database query though. Again, sorting can be done with `ORDER BY`, assuming this is SQL or any of its dialects. – Ultimater Apr 24 '18 at 04:23
  • You may wanna check `https://datatables.net/` for table sorting. – Karlo Kokkak Apr 24 '18 at 04:56
  • Is it more efficient to just requery the database or to sort the array in PHP? – Magearlik Apr 24 '18 at 08:02
  • array('Part Time') is because in_array wont let me compare row['work_type'] to a string. – Magearlik Apr 24 '18 at 08:03
  • `array_multisort` isn't the best way to sort a complex array. See https://stackoverflow.com/a/17364128/476. Ideally you'd probably want to sort right in the database though. – deceze Apr 24 '18 at 08:19
  • @Magearlik So change `in_array` to `strcasecmp($row['work_type'], 'Part Time') === 0` – Justinas Apr 24 '18 at 08:20

1 Answers1

0

Ok I resolved this by just getting the data again from the database. Apparently this is more efficient.

Magearlik
  • 523
  • 1
  • 6
  • 18