PHPackages                             tomkyle/transposer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. tomkyle/transposer

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

tomkyle/transposer
==================

A PHP library for transposing arrays and objects.

1.0.1(11mo ago)01MITPHPPHP ^8.3CI passing

Since Jun 9Pushed 11mo agoCompare

[ Source](https://github.com/tomkyle/transposer)[ Packagist](https://packagist.org/packages/tomkyle/transposer)[ RSS](/packages/tomkyle-transposer/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (5)Versions (3)Used By (0)

tomkyle/transposer
==================

[](#tomkyletransposer)

[![PHP Version](https://camo.githubusercontent.com/911a83e2aa6fe73660ab613629a95c76622bf03049a7344e80c5ea72d4ef9c7d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e302d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)[![Tests](https://camo.githubusercontent.com/d940ad7f0752e2cbe0d63c50dcebf329078807390051c41fe63258f1b5c4e182/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d70617373696e672d627269676874677265656e)](tests)

A lightweight, zero-dependency utility class for transposing two-dimensional associative arrays. Converts nested data structures from `[category][field] => value` format into `[field][label => field, category => value]` format, making the data suitable for table display where fields become rows and categories become columns.

Installation
------------

[](#installation)

Install via Composer:

```
composer require tomkyle/transposer
```

Requirements
------------

[](#requirements)

- PHP 8.3 or higher
- No additional dependencies

Overview
--------

[](#overview)

The IterableTransposer performs matrix-like transposition on associative arrays or iterables. It is particularly useful for transforming data that is grouped by categories into a format that can be easily displayed in tables or exported to formats like CSV.

- **Input**: Nested array with categories containing field-value pairs
- **Output**: Transposed array with fields as keys, each containing category-value pairs
- **Use case**: Converting grouped data into table-ready format

Basic Usage
-----------

[](#basic-usage)

The constructor accepts an optional label for the first column of the transposal result, which can be used to describe the fields. If no label is provided, the first column will not have a label. In this example, we will use the label "Metric" for the first column in the transposed array which carries the 1st-level key names (e.g., "revenue", "orders" …).

```
use tomkyle\Transposer\IterableTransposer;

$transposer = new IterableTransposer('Metric');

$data = [
    'Q1-2023' => [
        'revenue' => 125000,
        'orders' => 1250,
        'customers' => 800
    ],
    'Q2-2023' => [
        'revenue' => 138000,
        'orders' => 1380,
        'customers' => 920
    ],
    'Q3-2023' => [
        'revenue' => 142000,
        'orders' => 1420,
        'customers' => 980
    ]
];

$result = $transposer($data);
```

**Output:**

```
[
    'revenue' => [
        'Metric' => 'revenue',
        'Q1-2023' => 125000,
        'Q2-2023' => 138000,
        'Q3-2023' => 142000
    ],
    'orders' => [
        'Metric' => 'orders',
        'Q1-2023' => 1250,
        'Q2-2023' => 1380,
        'Q3-2023' => 1420
    ],
    'customers' => [
        'Metric' => 'customers',
        'Q1-2023' => 800,
        'Q2-2023' => 920,
        'Q3-2023' => 980
    ]
]
```

Constructor Options
-------------------

[](#constructor-options)

The constructor can take an optional label parameter that will be used as the header for the first column in the transposed result. If no label is provided, the first column will not have such a label.

First column will be labeled “Field Name”:

```
use tomkyle\Transposer\IterableTransposer;
$transposer = new IterableTransposer('Field Name');
$transposer = new IterableTransposer();
```

Method Parameters
-----------------

[](#method-parameters)

### \_\_invoke($inputArr, $label = null)

[](#__invokeinputarr-label--null)

- **$inputArr**: Array or iterable containing nested associative data
- **$label**: Optional runtime override for the label column name

```
$transposer = new IterableTransposer('Default');
$result = $transposer($data, 'Custom Label'); // Uses "Custom Label" instead of "Default"
```

Integration Examples
--------------------

[](#integration-examples)

```
$salesData = [
    'January' => ['online' => 50000, 'retail' => 30000, 'wholesale' => 20000],
    'February' => ['online' => 55000, 'retail' => 32000, 'wholesale' => 22000],
    'March' => ['online' => 60000, 'retail' => 35000, 'wholesale' => 25000]
];

$transposer = new IterableTransposer('Channel');
$tableData = $transposer($salesData);
```

After tranposal, the data can be used in various formats such as Markdown tables, Symfony Console tables, or exported to CSV. Its result looks like so:

```
Array
(
    [online] => Array
        (
            [Channel] => online
            [January] => 50000
            [February] => 55000
            [March] => 60000
        )

    [retail] => Array
        (
            [Channel] => retail
            [January] => 30000
            [February] => 32000
            [March] => 35000
        )

    [wholesale] => Array
        (
            [Channel] => wholesale
            [January] => 20000
            [February] => 22000
            [March] => 25000
        )

)

```

The result as a Markdown table would look like this:

```
| Channel   | January | February | March |
|-----------|---------|----------|-------|
| online    | 50000   | 55000    | 60000 |
| retail    | 30000   | 32000    | 35000 |
| wholesale | 20000   | 22000    | 25000 |
```

### With Symfony Console Tables

[](#with-symfony-console-tables)

```
use Symfony\Component\Console\Helper\Table;

$transposer = new IterableTransposer('Channel');
$tableData = $transposer($data);

$table = new Table($output);
$table->setHeaders(array_keys(reset($tableData)));

foreach ($tableData as $row) {
    $table->addRow($row);
}
$table->render();
```

### CSV Export

[](#csv-export)

```
$transposer = new IterableTransposer('Channel');
$csvData = $transposer($data);

$fp = fopen('export.csv', 'w');
// Write headers first
fputcsv($fp, array_keys(reset($csvData)));
// Write data rows
foreach ($csvData as $row) {
    fputcsv($fp, $row);
}
fclose($fp);
```

Error Handling
--------------

[](#error-handling)

The IterableTransposer is designed to be robust and handles edge cases gracefully:

```
$transposer = new IterableTransposer('Field');

// Empty input
$result = $transposer([]); // Returns []

// Non-nested data
$result = $transposer(['a', 'b', 'c']); // Returns []

// Mixed data types
$data = [
    'category1' => ['field1' => 'value1', 'field2' => 123],
    'category2' => ['field1' => null, 'field2' => true]
];
$result = $transposer($data); // Handles mixed types properly
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run tests with coverage:

```
composer test:coverage
```

Run static analysis:

```
composer analyse
```

Development
-----------

[](#development)

This project follows PSR-12 coding standards and includes:

- PHPUnit for testing
- PHPStan for static analysis
- PHP-CS-Fixer for code formatting
- Rector for automated refactoring
- File watching for continuous development

### Setup Development Environment

[](#setup-development-environment)

```
git clone https://github.com/tomkyle/transposer.git
cd iterable-transposer
composer install
npm install
```

### Development Workflow

[](#development-workflow)

The project uses npm scripts for development tasks:

```
# Watch files for changes (runs PHPStan, Rector, and tests automatically)
npm run watch

# Code quality tools
npm run phpcs          # Check code style (dry-run)
npm run phpcs:apply    # Fix code style

npm run phpstan        # Run static analysis

npm run rector         # Check for refactoring suggestions (dry-run)
npm run rector:apply   # Apply refactoring suggestions

# Testing
npm run phpunit        # Run tests with coverage
npm run phpunit:short  # Run tests without coverage
```

### File Watching

[](#file-watching)

The watch command monitors source and test files for changes and automatically runs the appropriate tools:

- **Source files** (`src/**/*.php`): Runs PHP-CS-Fixer, PHPStan, and Rector
- **Test files** (`tests/**/*.php`): Runs PHPUnit tests

Performance Considerations
--------------------------

[](#performance-considerations)

- **Memory**: Creates a new array structure; original data remains unchanged
- **Time Complexity**: $O(n \\times m)$ where $n$ = categories, $m$ = fields per category
- **Best For**: Small to medium datasets (thousands of records)
- **Large Data**: Consider streaming for very large datasets

API Reference
-------------

[](#api-reference)

### IterableTransposer::\_\_construct(?string $label = null)

[](#iterabletransposer__constructstring-label--null)

Creates a new transposer instance with an optional default label.

### IterableTransposer::\_\_invoke(iterable $inputArr, ?string $label = null): array

[](#iterabletransposer__invokeiterable-inputarr-string-label--null-array)

Transposes the input array and returns the result.

**Parameters:**

- `$inputArr`: Nested associative array or iterable
- `$label`: Optional label override for the first column

**Returns:** Transposed associative array

**Throws:** No exceptions; returns empty array for invalid input

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

### Guidelines

[](#guidelines)

- Follow PSR-12 coding standards
- Add tests for any new features
- Update documentation as needed
- Ensure all tests pass

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Changelog
---------

[](#changelog)

All notable changes to this project will be documented in the [CHANGELOG.md](CHANGELOG.md) file.

Support
-------

[](#support)

- [GitHub Issues](https://github.com/tomkyle/iterable-transposer/issues) for bug reports and feature requests
- [GitHub Discussions](https://github.com/tomkyle/iterable-transposer/discussions) for questions and community support

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance51

Moderate activity, may be stable

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

343d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/412560?v=4)[Carsten Witt](/maintainers/tomkyle)[@tomkyle](https://github.com/tomkyle)

---

Top Contributors

[![tomkyle](https://avatars.githubusercontent.com/u/412560?v=4)](https://github.com/tomkyle "tomkyle (4 commits)")

---

Tags

arraytransposetranspose arrayarray transpose

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tomkyle-transposer/health.svg)

```
[![Health](https://phpackages.com/badges/tomkyle-transposer/health.svg)](https://phpackages.com/packages/tomkyle-transposer)
```

###  Alternatives

[doctrine/collections

PHP Doctrine Collections library that adds additional functionality on top of PHP arrays.

6.0k411.1M1.2k](/packages/doctrine-collections)[symfony/property-access

Provides functions to read and write from/to an object or array using a simple string notation

2.8k295.3M2.5k](/packages/symfony-property-access)[nette/utils

🛠 Nette Utils: lightweight utilities for string &amp; array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.

2.1k394.3M1.5k](/packages/nette-utils)[league/config

Define configuration arrays with strict schemas and access values with dot notation

564302.2M24](/packages/league-config)[cuyz/valinor

Dependency free PHP library that helps to map any input into a strongly-typed structure.

1.5k9.2M108](/packages/cuyz-valinor)[aimeos/map

Easy and elegant handling of PHP arrays as array-like collection objects similar to jQuery and Laravel Collections

4.2k412.9k11](/packages/aimeos-map)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
