如何转置数组

时间:2017-05-04 07:24:05

标签: php arrays

如何使用php获取如下格式的数组,我想获得如下定义的simillar结构。

我的数组就像下面的命令一样,

$customarray = 
Array
(
    [0] => Finish1
    [1] => Hook1
    [2] => Material1
    [3] => Mounting1
)

Array
(
    [0] => Finish2
    [1] => Hook2
    [2] => Material2
    [3] => Mounting2
)

Array
(
    [0] => Finish3
    [1] => Hook3
    [2] => Material3
    [3] => Mounting3
)

结果数组想要格式化,

$resultantArray =
Array
(
    [0] => Finish1
    [1] => Finish2
    [2] => Finish3
)

Array
(
    [0] => Hook1
    [1] => Hook2
    [2] => Hook3
)

Array
(
    [0] => Material1
    [1] => Material2
    [2] => Material3
)
Array
(
    [0] => Mounting1
    [1] => Mounting2
    [2] => Mounting3
)

任何帮助都会被暗示,

感谢。

3 个答案:

答案 0 :(得分:1)

希望这会帮助你..

Try this code snippet here

<?php

ini_set('display_errors', 1);
$customarray = array(
    Array
        (
        0 => "Finish1",
        1 => "Hook1",
        2 => "Material1",
        3 => "Mounting1"
    ),
    Array
        (
        0 => "Finish2",
        1 => "Hook2",
        2 => "Material2",
        3 => "Mounting2"
    ),
    Array
        (
        0 => "Finish3",
        1 => "Hook3",
        2 => "Material3",
        3 => "Mounting3",
    )
);
$result=array();
for($x=0;$x<count($customarray);$x++)
{
    for($y=0;$y<count($customarray[$x]);$y++)
    {
        $result[$y][$x]=$customarray[$x][$y];//here we are flipping values
    }
}
print_r($result);

<强>输出:

Array
(
    [0] => Array
        (
            [0] => Finish1
            [1] => Finish2
            [2] => Finish3
        )

    [1] => Array
        (
            [0] => Hook1
            [1] => Hook2
            [2] => Hook3
        )

    [2] => Array
        (
            [0] => Material1
            [1] => Material2
            [2] => Material3
        )

    [3] => Array
        (
            [0] => Mounting1
            [1] => Mounting2
            [2] => Mounting3
        )

)

答案 1 :(得分:0)

这样做:

$a = []; //Your array
/*
    $a = array(
    Array
     (
      0 => "Finish1",
      1 => "Hook1",
      2 => "Material1",
      3 => "Mounting1"
     ),
Array
    (
    0 => "Finish2"
*/
$output = []; //output array
foreach($a as $key => $innerArr){
    foreach($innerArr as $val){
        $valKey = preg_replace('/[0-9]+/', '', $val);
        $output[$valKey][] = $val;
    }
}

答案 2 :(得分:0)

您可以使用某些array_mapcall_user_func_arrray 魔法来执行此操作

$a = [
    ['11', '12', '13'],
    ['21', '22', '23'],
    ['31', '32', '33'],
    ['41', '42', '43'],
];

$b = call_user_func_array('array_map', array_merge((array)function() {
    return func_get_args();
}, $a));

以下应该更容易理解,因为它没有array_merge

$b = call_user_func('array_map', function() {
    return func_get_args();
}, ...$a);

甚至更容易

$b = array_map(function() {
    return func_get_args();
}, ...$a);

如果你知道array_map的内部结构,你甚至可以通过传递null作为回调函数来将它缩短一点

$b = array_map(null, ...$a);