<?php
function array_transpose(array|object $object_or_array): array|object {
$levelOneType = gettype($object_or_array);
if (!in_array($levelOneType, ['array', 'object'])) {
throw new Exception("Fatal error: Uncaught TypeError: array_transpose(): Argument #1 ($object_or_array) must be of type object|array, $levelOneType given");
}
foreach ($object_or_array as $rowKey => $row) {
$levelTwoType = gettype($row);
if (!in_array($levelTwoType, ['array', 'object'])) {
throw new Exception("Fatal error: Uncaught TypeError: array_transpose(): Argument #1 ($object_or_array) must contain rows of type object|array, $levelTwoType given");
}
$result ??= ($levelTwoType === 'array' ? [] : (object)[]);
foreach ($row as $columnKey => $value) {
if ($levelTwoType === 'array') {
if ($levelOneType === 'array') {
$result[$columnKey][$rowKey] = $value;
} else {
$result[$columnKey]->$rowKey = $value;
}
} else {
if (!property_exists($result, $columnKey)) {
$result->$columnKey = ($levelOneType === 'array' ? [] : (object)[]);
}
if ($levelOneType === 'array') {
$result->{$columnKey}[$rowKey] = $value;
} else {
$result->{$columnKey}->$rowKey = $value;
}
}
}
}
return $result ?? ($levelOneType === 'array' ? [] : (object)[]);
}
$tests = [
[],
(object)[],
[['single' => 'row']],
['a' => [1], 'b' => [2, 3]],
[['id' => 1], ['id' => 2]],
[(object)['x' => 1, 'y' => [[2]]], (object)['a' => null, 'b' => "3"]],
(object)['foo' => (object)['bar' => 42], 'goo' => (object)['car' => 24]],
[[], []],
[[], [], [false]],
[[[]], [[]]],
];
foreach ($tests as $test) {
echo var_export(array_transpose($test), true) . "\n---\n";
}
- Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- array (
)
---
(object) array(
)
---
array (
'single' =>
array (
0 => 'row',
),
)
---
array (
0 =>
array (
'a' => 1,
'b' => 2,
),
1 =>
array (
'b' => 3,
),
)
---
array (
'id' =>
array (
0 => 1,
1 => 2,
),
)
---
(object) array(
'x' =>
array (
0 => 1,
),
'y' =>
array (
0 =>
array (
0 =>
array (
0 => 2,
),
),
),
'a' =>
array (
1 => NULL,
),
'b' =>
array (
1 => '3',
),
)
---
(object) array(
'bar' =>
(object) array(
'foo' => 42,
),
'car' =>
(object) array(
'goo' => 24,
),
)
---
array (
)
---
array (
0 =>
array (
2 => false,
),
)
---
array (
0 =>
array (
0 =>
array (
),
1 =>
array (
),
),
)
---
- Output for 7.4.0 - 7.4.33
- Parse error: syntax error, unexpected '|', expecting variable (T_VARIABLE) in /in/RRKlr on line 3
Process exited with code 255.
preferences:
118.21 ms | 407 KiB | 5 Q