如何使用循环和操作从1D数组创建2D?

时间:2017-11-20 01:03:36

标签: php arrays

如何在PHP中从一维数组创建二维?
例如,我有一个数组:

$a = Array
        (
            [0] => qwer
            [1] => asdfg
        )

我想把它转换成这样:

$b = Array
    (
        [0] => array
               (
                  [0] => qw
                  [1] => we
                  [2] => er
               )
        [1] => array 
              (
                  [0] => as
                  [1] => sd
                  [2] => df
                  [3] => fg
              )
    )

非常感谢您的回答。

1 个答案:

答案 0 :(得分:1)

我们可以使用substr,循环$a数组并将其存储在$b数组中。

<强> CODE:

$a = array(
        0 => 'qwer',
        1 => 'asdfg'
    );

$b = array();
$a_length = count($a);
for($i = 0; $i < $a_length; $i++){
    // Create new array
    $b[$i] = array();
    // Get the string length of $a element and minus it to 1
    for($j = 0; $j < (strlen($a[$i]) - 1); $j++){
        // Add it to our new array.
        $b[$i][] = substr($a[$i], $j, 2);
    }
}
echo "<pre>";
print_r($b);

<强>输出:

Array
(
    [0] => Array
        (
            [0] => qw
            [1] => we
            [2] => er
        )

    [1] => Array
        (
            [0] => as
            [1] => sd
            [2] => df
            [3] => fg
        )

)