|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2012-11-22 04:01 UTC] tagg_maiwald at yahoo dot com
Description:
------------
Two dimensional array inversion or transposition task is granular enough that it should be included as a PHP array_(name) function, instead of forcing scripters to "re-invent the wheel."
"array_invert" and "array_transpose" are two names which seem natural for this.
Test script:
---------------
<?php
function f_ary_trans_rc( $ary )
{
$ret_ary = Array( ) ;
foreach( $ary as $k_row => $ary_col )
{ foreach( $ary_col as $k_col => $v_node )
{ $ret_ary[ $k_col ][ $k_row ] = $v_node ;
} }
return $ret_ary ;
}
function f_ary_out( $ary )
{
$sz_ret = '' ;
foreach( $ary as $k_row => $ary_col )
{ foreach( $ary_col as $k_col => $v_node )
{ $sz_ret .= $v_node ;
}
$sz_ret .= "\n" ;
}
return $sz_ret ;
}
$ary_test = Array
( 'abc',
'def',
'ghi',
'123',
'456',
'789'
) ;
$ary_before = Array( ) ;
foreach( $ary_test as $key => $value )
{
$value = trim( $value ) ;
$value = strtoupper( $value ) ;
$ary_before[ ] = str_split( $value ) ;
}
echo '$ary_before:' . "\n" ;
echo f_ary_out( $ary_before ) ;
print_r( $ary_before ) ;
$ary_after = f_ary_trans_rc( $ary_before ) ;
echo "\n\n" . '$ary_after:' . "\n" ;
echo f_ary_out( $ary_after ) ;
print_r( $ary_after ) ;
?>
Expected result:
----------------
Row and column indices of the returned array will be inverted/transposed from that of the parameter array, with corresponding movement of the referenced nodes/values.
Actual result:
--------------
$ary_before:
ABC
DEF
GHI
123
456
789
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
)
[1] => Array
(
[0] => D
[1] => E
[2] => F
)
[2] => Array
(
[0] => G
[1] => H
[2] => I
)
[3] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[4] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[5] => Array
(
[0] => 7
[1] => 8
[2] => 9
)
)
$ary_after:
ADG147
BEH258
CFI369
Array
(
[0] => Array
(
[0] => A
[1] => D
[2] => G
[3] => 1
[4] => 4
[5] => 7
)
[1] => Array
(
[0] => B
[1] => E
[2] => H
[3] => 2
[4] => 5
[5] => 8
)
[2] => Array
(
[0] => C
[1] => F
[2] => I
[3] => 3
[4] => 6
[5] => 9
)
)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 22 07:00:01 2025 UTC |
$testarray = array_map('str_split', ['ABC', 'DEF', 'GHI']); $transpose = array_map(null, ...$testarray); var_dump($transpose);