SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/Rs.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13.  
  14. namespace Sprout\Helpers;
  15.  
  16. use InvalidArgumentException;
  17.  
  18. use PDOStatement;
  19.  
  20.  
  21. /**
  22.  * Functions to hack database query result sets
  23.  */
  24. class Rs
  25. {
  26.  
  27. /**
  28.   * Groups rows in a resultset (e.g. by category, date, ...)
  29.   *
  30.   * @param array|PDOStatement $rs Resultset, which MUST have an id column
  31.   * @param string $group_id The column with the field to group by,
  32.   * e.g. cat_id
  33.   * @param string $group_fields Extra data for the group segments. The keys
  34.   * are the fields for each group, and the values are the
  35.   * corresponding field names in the result set. For example,
  36.   * ['name' => 'cat_name', 'slug' => 'cat_slug']
  37.   * @return array Grouped rows. The key is the group id, and the value is
  38.   * an array with key 'rows', and a matching key for each of the
  39.   * specified $group_fields
  40.   */
  41. public static function groupByField($rs, $group_id, array $group_fields = array()) {
  42. if (!is_array($rs) and !($rs instanceof PDOStatement)) {
  43. throw new InvalidArgumentException('$rs must be array or PDOStatement');
  44. }
  45.  
  46. $grouped = array();
  47. foreach ($rs as $row) {
  48. if (!isset($row['id'])) {
  49. throw new InvalidArgumentException('$rs must have an id column');
  50. }
  51. $key = $row[$group_id];
  52. if (!isset($grouped[$key])) {
  53. $grouped[$key] = array('rows' => array());
  54. foreach ($group_fields as $field => $alias) {
  55. if ($field == 'rows') continue;
  56. $grouped[$key][$field] = $row[$alias];
  57. }
  58. }
  59. foreach ($group_fields as $field => $alias) {
  60. unset($row[$alias]);
  61. }
  62. $grouped[$key]['rows'][$row['id']] = $row;
  63. }
  64. return $grouped;
  65. }
  66. }
  67.