【问题标题】:Where is the PHP array insertion statement documented? [closed]PHP 数组插入语句记录在哪里? [关闭]
【发布时间】:2021-07-23 08:21:17
【问题描述】:

在 PHP 中,以下语句既定义了一个数组,又将一个元素插入到数组中:

$arr[] = $element

这个语句的使用示例(在循环中)如下所示。 (来自PHP MySQli tutorial):

while ($row = $result->fetch_assoc())
{
  $ids[] = $row['id'];
  $names[] = $row['name'];
  $ages[] = $row['age'];
}
  1. PHP 官方文档在哪里记录了这种语法?

  2. 请解释一下这个语法。

【问题讨论】:

  • 有关数组的官方 PHP 页面(Mat 提供了一个链接)将此功能称为“数组追加”。
  • 您需要更清楚您要查找的信息。当然它被称为数组追加,因为您将值追加(推送)到数组。您描述的语法称为数组自动激活。即使之前没有定义,它也会创建一个数组。

标签: php


【解决方案1】:

array_push in loop(您正在使用 while 循环)和初始化数组的值($arr[] = $element)并没有什么特别之处。唯一的区别是您通过 while 循环将值推入数组并最初使用赋值运算符声明。

在您的情况下,您已将 $element 初始化为数组

$arr[] = "123"; //Lets say 123 is $element
$arr[] = "NAME"; //Same way, you can repeat in next line as well
$arr[] = "45";

echo '<pre>';
print_r($arr);

// And the output was 
Array (
    [0] => 123
    [1] => NAME
    [2] => 45
)

下一个语句是

while ($row = $result->fetch_assoc())
{
  $ids[] = $row['id'];// Lets say 123 is $row['id'];
  $names[] = $row['name']; //Lets say NAME is $row['name'];
  $ages[] = $row['age']; //Lets say 45 is $row['age'];
}

//The output will be same if only one row exist in the loop
Array (
 [0] => 123
 [1] => NAME
 [2] => 45
 .................. // Based on while loop rows
)

符号 [] 会将值推入数组,因为您没有在括号之间提及任何键。

【讨论】:

    【解决方案2】:
    $ids[] = $row['id'];  
    

    这里我们将返回的id 元素(来自 SQL 查询)分组到一个数组中。因此,最后,ids 数组将存储来自 SQL 查询的所有 id 元素;其他数组也是如此。

    语法$id [] = $value 表示我们将$value 元素推入数组。

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 2013-05-25
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 2011-04-03
      • 1970-01-01
      相关资源
      最近更新 更多