就像向数组中添加元素一样简单:
//Setup blank array
$example = array();
//Create a loop, for example purposes.
foreach(range(0, 99) as $i){
//Create random variable that we'll add to our array
$randVar = mt_rand(1, 90000);
//$i will be our array key/index
$example[$i] = randVar;
}
//var_dump the array so you can see the structure / end result
var_dump($example);
您也可以像这样创建它:
//Create random array key/index
$myRandKey = mt_rand(1, 90000);
//Create random variable value.
$myRandVar = mt_rand(1, 90000);
//Setup an array
$example = array(
$myRandKey => $myRandVar
);
//Another array key that we'll add to our array
$secondKey = 'test';
//Add it
$example[$secondKey] = 'This is just an example!';
//Dump out the array
var_dump($example);
array_push 也可以工作(使用 mysql_fetch_assoc,就像在你的例子中一样):
$example = array();
while($row = mysql_fetch_assoc($result)){
array_push($example, $row);
}
var_dump($example);
在您的特定示例中(因为您添加了代码):
print_r($new_array[] = $row[]);
应改为:
print_r($new_array[] = $row);
在您的代码中,我将其更改为:
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[] = $row;
}
或者,如果您想通过唯一列(例如主键)来键入数组:
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[$row['id']] = $row;
}