如何在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
)
)
非常感谢您的回答。
答案 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
)
)