我想做这样的事情:
<?php
$times[monday] = ['7-10', '3-5', '1-6'];
$times[tuesday] = ['5-9', '12-15', '19-22'];
echo $times[monday][2]
?>
此代码将回显3-5
,因为这是数组$times[monday]
中的第二项。
然而,这只是出错:
Notice: Use of undefined constant monday - assumed 'monday' in /var/www/sch/index.php on line 2
Notice: Use of undefined constant tuesday - assumed 'tuesday' in /var/www/sch/index.php on line 3
Notice: Use of undefined constant monday - assumed 'monday' in /var/www/sch/index.php on line 4
答案 0 :(得分:3)
<?php
$times['monday'] = array('7-10', '3-5', '1-6');
$times['tuesday'] = array('5-9', '12-15', '19-22');
echo $times['monday'][2]
?>
您需要引用数组字符串元素标识符(例如&#39; monday&#39;)并使数组成为多维的,如图所示。
如果没有引号,字符串monday
将作为常量处理。
请注意代码:
echo $times['monday'][2]
将回显1-6
,因为数组基于0(元素从0开始)。如果你想要3-5
,那就是:
echo $times['monday'][1]
答案 1 :(得分:2)
您忘记了引号,要初始化数组,您应该在括号前添加array
关键字:
<?php
$times['monday'] = array('7-10', '3-5', '1-6');
$times['tuesday'] = array('5-9', '12-15', '19-22');
echo $times['monday'][2];
?>