0 follower

Final Class Yiisoft\Db\Helper\DbArrayHelper

InheritanceYiisoft\Db\Helper\DbArrayHelper

Array manipulation methods.

Public Methods

Hide inherited methods

Method Description Defined By
arrange() Arranges the array of rows according to specified keys. Yiisoft\Db\Helper\DbArrayHelper
index() Indexes the array of rows according to a specified key. Yiisoft\Db\Helper\DbArrayHelper
isAssociative() Returns a value indicating whether the given array is an associative array. Yiisoft\Db\Helper\DbArrayHelper
multisort() Sorts an array of objects or arrays (with the same structure) by one or several keys. Yiisoft\Db\Helper\DbArrayHelper
normalizeExpressions() Normalizes raw input into an array of expression values. Yiisoft\Db\Helper\DbArrayHelper
toArray() Converts an object into an array. Yiisoft\Db\Helper\DbArrayHelper

Method Details

Hide inherited methods

arrange() public static method

Arranges the array of rows according to specified keys.

For example:

$array = [
    ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
    ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
];
$result = DbArrayHelper::arrange($rows, ['id']);

The result will be a multidimensional array arranged by id:

[
    '123' => [
        ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
    ],
    '345' => [ // all elements with this index are present in the result array
        ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
        ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
    ]
]

Another example:

 $result = DbArrayHelper::arrange($rows, ['id', 'device'], 'data');
 ```

The result will be a multidimensional array arranged by `id` on the first level, by `device` on the second level
and indexed by `data` on the third level:

```php
[
    '123' => [
        'laptop' => [
            'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
        ]
    ],
    '345' => [
        'tablet' => [
            'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
        ],
        'smartphone' => [
            'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
        ]
    ]
]
public static array[]|object[] arrange ( array[] $rows, string[] $arrangeBy = [], Closure|string|null $indexBy null, Closure|null $resultCallback null )
$rows array[]

The array of rows that needs to be arranged.

$arrangeBy string[]

The array of keys that will be used to arrange the input array by one or more keys.

$indexBy Closure|string|null

The column name or anonymous function which result will be used to index the array.

$resultCallback Closure|null

The callback function that will be called with the result array. This can be used to modify the result before returning it.

return array[]|object[]

The arranged array.

                public static function arrange(
    array $rows,
    array $arrangeBy = [],
    Closure|string|null $indexBy = null,
    ?Closure $resultCallback = null,
): array {
    if (empty($rows)) {
        return [];
    }
    if (empty($arrangeBy)) {
        return self::index($rows, $indexBy, $resultCallback);
    }
    $arranged = [];
    foreach ($rows as $element) {
        $lastArray = &$arranged;
        foreach ($arrangeBy as $group) {
            $value = (string) $element[$group];
            if (!isset($lastArray[$value])) {
                $lastArray[$value] = [];
            }
            $lastArray = &$lastArray[$value];
        }
        /** @psalm-suppress MixedArrayAssignment */
        $lastArray[] = $element;
        unset($lastArray);
    }
    /** @var array[] $arranged */
    if ($indexBy !== null || $resultCallback !== null) {
        self::indexArranged($arranged, $indexBy, $resultCallback, count($arrangeBy));
    }
    return $arranged;
}

            
index() public static method

Indexes the array of rows according to a specified key.

For example:

$array = [
    ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
    ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
];
$result = DbArrayHelper::index($array, 'id');

The result will be an associative array, where the key is the value of id attribute

[
    '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
    // The second element of an original array is overwritten by the last element because of the same id
]
public static array[]|object[] index ( array[] $rows, Closure|string|null $indexBy null, Closure|null $resultCallback null )
$rows array[]

The array of rows that needs to be indexed.

$indexBy Closure|string|null

The column name or anonymous function which result will be used to index the array.

$resultCallback Closure|null

The callback function that will be called with the result array. This can be used to modify the result before returning it.

return array[]|object[]

The indexed array.

                public static function index(
    array $rows,
    Closure|string|null $indexBy = null,
    ?Closure $resultCallback = null,
): array {
    if (empty($rows)) {
        return [];
    }
    if ($indexBy !== null) {
        if (is_string($indexBy)) {
            $indexes = array_column($rows, $indexBy);
        } else {
            $indexes = array_map($indexBy, $rows);
        }
    }
    if ($resultCallback !== null) {
        $rows = ($resultCallback)($rows);
    }
    /** @psalm-suppress MixedArgument */
    return !empty($indexes) ? array_combine($indexes, $rows) : $rows;
}

            
isAssociative() public static method

Returns a value indicating whether the given array is an associative array.

An array is associative if all its keys are strings.

Note that an empty array won't be considered associative.

public static boolean isAssociative ( array $array )
$array array

The array being checked.

return boolean

Whether the array is associative.

                public static function isAssociative(array $array): bool
{
    if (empty($array)) {
        return false;
    }
    foreach ($array as $key => $_value) {
        if (is_string($key)) {
            return true;
        }
    }
    return false;
}

            
multisort() public static method

Sorts an array of objects or arrays (with the same structure) by one or several keys.

public static void multisort ( array &$array, string $key )
$array array

The array to be sorted. The array will be modified after calling this method.

$key string

The key(s) to be sorted by.

                public static function multisort(
    array &$array,
    string $key,
): void {
    if (empty($array)) {
        return;
    }
    $column = array_column($array, $key);
    array_multisort(
        $column,
        SORT_ASC,
        SORT_NUMERIC,
        /**
         * This fix is used for cases when the main sorting specified by columns has equal values without it will
         * lead to Fatal Error: Nesting level too deep - recursive dependency?
         */
        range(1, count($array)),
        SORT_ASC,
        SORT_NUMERIC,
        $array,
    );
}

            
normalizeExpressions() public static method

Normalizes raw input into an array of expression values.

public static array normalizeExpressions ( array|Yiisoft\Db\Expression\ExpressionInterface|string $raw )
$raw array|Yiisoft\Db\Expression\ExpressionInterface|string

Raw input to be normalized. It can be:

  • an array of expression values;
  • a single expression object;
  • a string with comma-separated expression values.
return array

An array of normalized expressions.

                public static function normalizeExpressions(array|ExpressionInterface|string $raw): array
{
    /**
     * @psalm-suppress PossiblyInvalidArgument,FalsableReturnStatement
     */
    return match (gettype($raw)) {
        GettypeResult::ARRAY => $raw,
        GettypeResult::STRING => preg_split('/\s*,\s*/', trim($raw), -1, PREG_SPLIT_NO_EMPTY),
        default => [$raw],
    };
}

            
toArray() public static method

Converts an object into an array.

public static array toArray ( array|object $object )
$object array|object

The object to be converted into an array.

return array

The array representation of the object.

                public static function toArray(array|object $object): array
{
    if (is_array($object)) {
        return $object;
    }
    if ($object instanceof JsonSerializable) {
        /** @var array */
        return $object->jsonSerialize();
    }
    if ($object instanceof Traversable) {
        return iterator_to_array($object);
    }
    return get_object_vars($object);
}