首页 > 解决方案 > PHP 数组插入语句记录在哪里?

问题描述

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

$arr[] = $element

下面显示了使用此语句的示例(在循环中)。(它来自这个PHP MySQli 教程):

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

  2. 请解释这个语法。

标签: php

解决方案


循环中的array_push(您正在使用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
)

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


推荐阅读