Php 在for循环内创建关联数组
嗨,我已经创建了一个数组,里面有一个for循环。在到达for循环之前,数组中没有任何数据。我想在我目前所做的工作中添加一个关联数组。例如,我的阵列当前正在输出Php 在for循环内创建关联数组,php,arrays,loops,Php,Arrays,Loops,嗨,我已经创建了一个数组,里面有一个for循环。在到达for循环之前,数组中没有任何数据。我想在我目前所做的工作中添加一个关联数组。例如,我的阵列当前正在输出 [0] => Array ( [0] => Version 5 [1] => Feb-16 [2] => gary [3] => 80 [4] => P
[0] => Array
(
[0] => Version 5
[1] => Feb-16
[2] => gary
[3] => 80
[4] => P
)
我希望它有标题而不是数字
[0] => Array
(
Version => Version 5
Date => Feb-16
Name => gary
RandNum => 80
Letter => P
}
我不知道我该如何适应我的循环,如果我的不同列包含这些标题,我该如何适应。下面是我当前的代码。它在顶部输出数组
for($i = 0; $i <= 3; $i++){
for($j = 0; $j <= 4; $j++){
if ($j == 0){
$times_table[$i][$j]= "Version 5" ;
}
else if ($j == 1){
$cur_date = date("M-y", $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i][$j]= "<strong>" . $cur_date . "</strong>" ;
}
else{
$times_table[$i][$j]= "gary" ;
}
if ($j == 3) {
$numbers = mt_rand(1, 100);
$times_table[$i][$j]= $numbers ;
}
if ($j == 4){
if($i == 0 || $i == 3)
{
$pay = "P";
$times_table[$i][$j]= $pay ;
}
else{
$int = "I";
$times_table[$i][$j]= $int ;
}
}
}
}
对于($i=0;$i请尝试此
for($i = 0; $i <= 3; $i++){
for($j = 0; $j <= 4; $j++){
if ($j == 0){
$times_table[$i]['Version']= "Version 5" ;
}
else if ($j == 1){
$cur_date = date("M-y", $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i]['Date']= "<strong>" . $cur_date . "</strong>" ;
}
else{
$times_table[$i]['Name']= "gary" ;
}
if ($j == 3) {
$numbers = mt_rand(1, 100);
$times_table[$i]['RandNum']= $numbers ;
}
if ($j == 4){
if($i == 0 || $i == 3)
{
$pay = "P";
$times_table[$i]['Letter']= $pay ;
}
else{
$int = "I";
$times_table[$i]['Letter']= $int ;
}
}
}
}
对于($i=0;$i对于($i=0;$i您可以创建如下关联数组:
$a=array("Version"=> "Version 5",
"Date"=> "Feb-16",
"Name" => "gary",
"RandNum" => 80,
"Letter" => "P"
)
要在for循环中访问此数组,请使用$a['key']
。例如,要访问version5,请使用$a['version']
,要访问Feb-16,请使用$a['Date']
在我看来,不需要第二个for循环。您应该知道,您可以创建如下关联数组:
<?php
$times_table = [];
$times_tables[] = [
'Version' => 'Version 5',
'Date' => 'Feb-16',
'Name' => 'gary',
'RandNum' => '80',
'Letter' => 'P',
];
你能描述一下你想要的多维数组的最终输出吗?@jiboulex我想他们想要的是“标题而不是数字”他们已经包含了建议的输出。该死,你比我快了。谢谢你的回答。我可以问一下为什么键不在第一个数组中。为什么要创建第二个数组$times\u tables有一个也是唯一的数组:$times\u table,它是多维的
<?php
$times_table = [];
$times_tables[] = [
'Version' => 'Version 5',
'Date' => 'Feb-16',
'Name' => 'gary',
'RandNum' => '80',
'Letter' => 'P',
];
<?php
$times_table = [];
for($i = 0; $i <= 3; $i++){
$times_table[$i]['Version']= "Version 5" ;
$cur_date = date("M-y", $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i]['Date']= "<strong>" . $cur_date . "</strong>" ;
$times_table[$i]['Name']= "gary" ;
$numbers = mt_rand(1, 100);
$times_table[$i]['RandNum']= $numbers ;
switch ($i) {
case 0:
case 3:
$letter = 'P';
break;
default:
$letter = 'I';
}
$times_table[$i]['Letter']= $letter;
}