【问题标题】:PHP define array with sub arrays as an indexPHP用子数组定义数组作为索引
【发布时间】:2020-01-02 23:16:06
【问题描述】:

我正在使用一个 PHP 文件来定义一些要在另一个应用程序中使用的数据。

我认为这是一种有效的方式来声明我的数组.. 使用子数组作为索引。

但显然不是..

//question 1
$quiz['question'][0] = "xxx";
$quiz['question'][0]['answer'][0] = "xxx";
$quiz['question'][0]['answer'][1] = "xxx";
$quiz['question'][0]['answer'][2] = "xxx";
$quiz['question'][0]['answer'][3] = "xxx";
$quiz['question'][0]['answer'][4] = "xxx";  

我如何正确定义这些容易/易读的数组?

我目前收到此错误/警告:

警告:非法字符串偏移 'answer'

【问题讨论】:

  • 为什么你会期望一个数组 === 一个字符串?
  • 你想用这段代码实现什么?很清楚为什么它不起作用,但不清楚你为什么希望它起作用。

标签: php arrays sub-array


【解决方案1】:

您在第一行明确表示 $quiz['question'][0] 是一个字符串,然后您尝试将其视为一个数组,这就是您收到此错误的原因

【讨论】:

  • DOH!.. 你是完全正确的!应该是:$quiz['question'][0]['question'] 感谢您关注主题并发布我的错误(已接受)
【解决方案2】:

如何定义,一种方式

$quiz['question'][0]['question'] = "How to define an array";
$quiz['question'][0]['answer'][0] = "Like this";
$quiz['question'][0]['answer'][1] = "or like that";
$quiz['question'][0]['answer'][2] = "or maybe like the other";
print_r($quiz);

结果

Array
(
    [question] => Array
        (
            [0] => Array
                (
                    [question] => How to define an array
                    [answer] => Array
                        (
                            [0] => Is it like this
                            [1] => Or isit like that
                            [2] => Or is it like the other
                        )

                )

        )

)

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 2015-12-15
    • 2011-08-15
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2014-04-29
    相关资源
    最近更新 更多