数组(有些键带有数组,有些是单数)


Arrays (some keys with arrays, some singular)

在开发php类时,我在php中遇到了一件非常有趣的事情。如果我要创建一个数组,有些是单个键,有些是在该键内有数组,它只返回数字,而不是数组键。为什么会这样?我该怎么解决?

<?php
    $example = array('name' => array('required' => true), 'email');
    foreach($example as $field => $value) {
        echo $field;
    }
?>

这将返回name0,而不是nameemail

您可能想要这个::

<?php
    $example = array('name' => array('required' => true), 'email');
    foreach($example as $field => $value) {
        if(is_array($value)){
          echo $field;
        }else{
          echo $value;
        }
    }
?>

因为您没有为元素'email'定义键。如果你会这样做:

$example = array('name' => array('required' => true), 'email' => 'something@isp.com');

你会得到:

name email

你也可以这样做:

$example = array('name' => array('required' => true), 'email' => '');

并且不必为"email"元素定义值。

我猜"email"不是一个键,而是一个元素。严格来说,数组键是"name",0。

如果你想显示姓名电子邮件

<?php
    $example = array('name' => array('required' => true), 'email'=>array());
    foreach($example as $field => $value) {
        echo $field;
    }
?>