我想制作如下数组:
array(
0 => array ( 0 => array (q,a,alt),
1 => array (q,a,alt),
2 => array (q,a,alt)
),
1 => array ( 0 => array (q,a,alt),
1 => array (q,a,alt),
2 => array (q,a,alt)
),
2 => array ( 0 => array (q,a,alt),
1 => array (q,a,alt),
2 => array (q,a,alt)
)
);
我遍历了所有地方都找不到解决方案。下面是我的代码:
<?php
$mainArray = array();
$ans = array('q', 'a', 'att');
for($i = 0; $i < 3; $i++) {
$mainArray[$i] = array();
for($j = 0; $j < 3; $j++) {
$mainArray[$i][$j] = array('q','a','att');
}
}
print_r($mainArray);
?>
我得到的是错误的东西。
下面是我的输出:
Array ( [0] => Array ( [0] => Array ( [0] => q [1] => a [2] => att ) [1] => Array ( [0] => q [1] => a [2] => att ) [2] => Array ( [0] => q [1] => a [2] => att ) ) [1] => Array ( [0] => Array ( [0] => q [1] => a [2] => att ) [1] => Array ( [0] => q [1] => a [2] => att ) [2] => Array ( [0] => q [1] => a [2] => att ) ) [2] => Array ( [0] => Array ( [0] => q [1] => a [2] => att ) [1] => Array ( [0] => q [1] => a [2] => att ) [2] => Array ( [0] => q [1] => a [2] => att ) ) )
答案 0 :(得分:0)
实际上比您想象的要容易得多。
PHP具有一个名为array_fill的函数,该函数将创建一个从'键'到'有'值'的数组。
$ans = array('q', 'a', 'att');
$no = 3;
$arr = array_fill(0, $no, $ans);
var_dump($arr);
输出:
array(3) {
[0]=>
array(3) {
[0]=>
string(1) "q"
[1]=>
string(1) "a"
[2]=>
string(3) "att"
}
[1]=>
array(3) {
[0]=>
string(1) "q"
[1]=>
string(1) "a"
[2]=>
string(3) "att"
}
[2]=>
array(3) {
[0]=>
string(1) "q"
[1]=>
string(1) "a"
[2]=>
string(3) "att"
}
}