0

Array_merge 和 array_merge_recursive 没有按预期工作,创建更多索引而不是将数组推到一起并保留索引号。请参阅下面的输入/所需输出:

Array (
    [0] => array(
        [0] => "string1",
        [1] => "string2",
        [2] => "string3"
    ),
    [1] => array(
        [0] => "string4",
        [1] => "string5",
        [2] => "string6"
    ),
    [2] => array(
        [0] => "string7",
        [1] => "string8",
        [2] => "string9"
    )
)

期望的输出:

Array (
    [0] => array("string1","string4","string7"),
    [1] => array("string2","string5","string8"),
    [2] => array("string3","string6","string9")

)

编辑:

也许不是最好的例子;我想获得相同的结果,但每个嵌套数组中的键数不相等。请参阅下面的更好示例:

<?php
$array = Array (
[0] => array(
    [0] => "string1",
    [1] => "string2",
    [2] => "string3"
    ),
[1] => array(
    [0] => "string4",
    [1] => "string5",
    [2] => "string6"
    ),
[2] => array(
    [0] => "string7",
    [1] => "string8",
    [2] => "string9"
    ),
[3] => array(
    [0] => "string10",
    [1] => "string11",
    [2] => "string12"
    )
);

$output=array();
    for($0=0;$j<count($array[0]);$j++){
        $output[$j] = array();
    }

for($i=0;$i<count($array);$i++){
    for($0=0;$j<count($array[0]);$j++){
        $output[$j] = array_push($output[$j],$column_values[$i][$j]);
    }
}


?>

但是当我这样做时,我在 $output 数组中得到了正确数量的键,但它们都包含一个 bool(false)。有什么帮助吗?

这是所需的输出:

Array (
    [0] => array("string1","string4","string7","string10"),
    [1] => array("string2","string5","string8","string11"),
    [2] => array("string3","string6","string9","string12")
)
4

3 回答 3

1

这是为这种数组结构制作一个数组,因此您可以根据需要更改代码...

<pre>
<?php
    $array = array(array("string1","string2","string3"),array("string4","string5","string6"),array("string7","string8","string9"));
    $output=array();
    for($i=0;$i<count($array[0]);$i++){
        for($j=0;$j<count($array[0]);$j++){
            $output[$i][$j] = $array[$j][$i];
        }
    }

    print_r($output);
?>
</pre>
于 2012-05-24T18:50:04.930 回答
0

知道了。最后一个循环应该简单地array_push($output[$j],$column_values[$i][$j]);而不是试图设置变量$output[$j] = array_push(Yadda,yadda)

于 2012-05-25T19:25:58.427 回答
0

这是针对您的“第二种”情况:

<?php

    $array = array(array("string1","string2","string3"),array("string4","string5","string6"),array("string7","string8","string9"),array("string10","string11","string12"));
    $output=array();

    for($i=0;$i<count($array[0]);$i++){
        for($j=0;$j<=count($array[0]);$j++){
            $output[$i][$j] = $array[$j][$i];
        }
    }
    print_r($output);
?>
于 2012-05-25T22:51:40.013 回答