如何在PHP中正确声明/定义关联数组?

时间:2015-05-21 12:07:27

标签: php arrays multidimensional-array associative-array error-reporting

我编写了一个程序来定义一个名为$aFilter的关联数组,并尝试打印它,但我无法做到。我尝试了两种方法来实现这一目标但却无法成功。以下是我尝试的两种方式。

方式1:

<!DOCTYPE html>
<html>
<body>

<?php
$aFilter = Array
        (
            ['pages'] => 1,
            ['photo'] => 1,
            ['link'] => 1,
            ['event'] => 1,
            ['friend'] => 1,
            ['user_status'] => 1,
            ['poll'] => 1,
            ['quiz'] => 1,
            ['market'] => 1,
            ['apps'] => 1
        )
        print_r($aFilter);
?>

</body>
</html>

方式2:

<!DOCTYPE html>
<html>
<body>

<?php
$aFilter = Array
        (
            ['pages'] => 1
            ['photo'] => 1
            ['link'] => 1
            ['event'] => 1
            ['friend'] => 1
            ['user_status'] => 1
            ['poll'] => 1
            ['quiz'] => 1
            ['market'] => 1
            ['apps'] => 1
        )
        print_r($aFilter);
?>

</body>
</html>

执行上述两个代码后,我的屏幕显示空白。没有任何错误或警告。为什么会这样?如何在不对php.ini文件设置进行任何更改的情况下在网页上显示错误和警告?

有人可以纠正我正在制造的错误并帮助我吗?

3 个答案:

答案 0 :(得分:4)

在定义数组后忘记了;。 并且在定义数组时也不要使用[]。 More info on array's.

$aFilter = Array(
            'pages' => 1,
            'photo' => 1,
            'link' => 1,
            'event' => 1,
            'friend' => 1,
            'user_status' => 1,
            'poll' => 1,
            'quiz' => 1,
            'market' => 1,
            'apps' => 1
        );
        print_r($aFilter);

print_r()以人类可读的方式显示有关变量的信息。 这不是您需要编写的代码。

答案 1 :(得分:3)

在数组定义之后,两种方式都缺少;,而方法2在每个数组元素之后缺少, s。此外,两种方式都应使用'elName' => 'elValue',而不是['elName'] => 'elValue',

答案 2 :(得分:3)

问题是: -

  1. 忘了;定义数组后。
  2. 当您对值进行硬编码时,您需要将索引放在不带括号的位置。
  3. 所以这样写: -

    Sub Unzip()
      Set fso = CreateObject("Scripting.FileSystemObject")
    
      For Each f In fso.GetFolder("C:\Users\Jimbo\Documents\Process\_ThisWeek").Files
        If LCase(fso.GetExtensionName(f)) = "zip" And Left(f.Name, 3) = "Health" Then
          Unzip f.Path, "C:\Users\Jimbo\Documents\Process\_ThisWeek"
        End If
    
        'If the extraction location does not exist create it
        Set fso = CreateObject("Scripting.FileSystemObject")
    
        If NOT fso.FolderExists(f.path) Then
          fso.CreateFolder(f.path)
        End If
    
        'Extract the contants of the zip file
        set objShell = CreateObject("Shell.Application")
        set FilesInZip = objShell.NameSpace(f.name).items
        objShell.NameSpace(f.path).CopyHere(f.name)
    
        Set fso = Nothing
        Set objShell = Nothing
      Next
    End Sub