3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 namespace Civi\Api4\Generic
;
15 * Container for api results.
17 class Result
extends \ArrayObject
{
35 * Return first result.
38 public function first() {
39 foreach ($this as $values) {
49 public function last() {
50 $items = $this->getArrayCopy();
51 return array_pop($items);
58 public function itemAt($index) {
59 $length = $index < 0 ?
0 - $index : $index +
1;
60 if ($length > count($this)) {
63 return array_slice(array_values($this->getArrayCopy()), $index, 1)[0];
67 * Re-index the results array (which by default is non-associative)
69 * Drops any item from the results that does not contain the specified key
73 * @throws \API_Exception
75 public function indexBy($key) {
76 $this->indexedBy
= $key;
79 foreach ($this as $values) {
80 if (isset($values[$key])) {
81 $newResults[$values[$key]] = $values;
85 throw new \
API_Exception("Key $key not found in api results");
87 $this->exchangeArray($newResults);
93 * Returns the number of results
97 public function count() {
98 $count = parent
::count();
99 if ($count == 1 && is_array($this->first()) && array_keys($this->first()) == ['row_count']) {
100 return $this->first()['row_count'];
106 * Reduce each result to one field
111 public function column($name) {
112 return array_column($this->getArrayCopy(), $name, $this->indexedBy
);