<?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("Error: array_transpose() expects parameter 1 to be an array or object, $levelOneType given");
}
$result = [];
foreach ($object_or_array as $rowKey => $row) {
$levelTwoType = gettype($row);
if (!in_array($levelTwoType, ['array', 'object'])) {
throw new Exception("Error: array_transpose() expects parameter 1 to contain rows of arrays or objects, $levelTwoType given");
}
foreach ($row as $columnKey => $value) {
$result[$columnKey][$rowKey] = $value;
}
}
return $result;
}
$names = ['Anne', 'Burt', 'Chad', 'Dawn'];
$ages = [18, 22, 20, 21];
$pets = ['dog', 'cat', 'fish', 'bird'];
var_export(array_transpose(compact(['names', 'ages', 'pets'])));
- 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 (
0 =>
array (
'names' => 'Anne',
'ages' => 18,
'pets' => 'dog',
),
1 =>
array (
'names' => 'Burt',
'ages' => 22,
'pets' => 'cat',
),
2 =>
array (
'names' => 'Chad',
'ages' => 20,
'pets' => 'fish',
),
3 =>
array (
'names' => 'Dawn',
'ages' => 21,
'pets' => 'bird',
),
)
- Output for 7.4.0 - 7.4.33
- Parse error: syntax error, unexpected '|', expecting variable (T_VARIABLE) in /in/jOQte on line 3
Process exited with code 255.
preferences:
112.88 ms | 407 KiB | 5 Q