简体   繁体   English

在PHP中用array()和方括号声明数组的冗余

[英]Redundant in declaring an array with array() and square brackets in PHP

This could probably sound silly, but my question is about arrays and their syntax: 这听起来可能很愚蠢,但是我的问题是关于数组及其语法的:

Isn't redundant to declare an array with this syntax? 使用这种语法声明数组是否多余?

$data[] = array(
    'ct_id' => $row->ct_id,
    'association' => $row->association_name,
    'designation' => $row->designation_name,
    'license_number' => $row->license_number,
    'license_date' => $row->license_date ? date("jS F, Y", strtotime($row->license_date)) : '',
    'date_added' => date("jS F, Y", strtotime($row->date_added))
);

Should the declaration of the array be sufficient to define an array? 数组的声明是否足以定义一个数组?

This code happens in a foreach loop like that: 这段代码发生在这样的foreach循环中:

foreach ($this->something->result() as $row) {..}

There are two things going on here. 这里有两件事。

array(...)

is one syntax to define an array in PHP. 是在PHP中定义数组的一种语法。

$data[] = ...

takes whatever is to the right of the equals sign and appends it to the array contained in $data . 取等号右边的任何内容, 并将附加$data包含的数组中。

So your result would look like: 因此,您的结果将如下所示:

$data => array(
    array(
        ...
    )
)

You should declared array without 【】 您应声明不带【的数组】

If you want a new element to add in array use 【】 like below, 如果您想在数组中添加一个新元素,请使用下面的【】,

$data【"test key"】= "test value"; $ data【“测试键”】=“测试值”;

So array() is for array initialization and 【】is for add new element. 所以array()用于数组初始化,【】用于添加新元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM