在PHP中使用=>

saw*_*awu 10 php

这在PHP中是什么意思,什么时候使用它?

 =>
Run Code Online (Sandbox Code Playgroud)

另一个例子.

 foreach ($parent as $task_id => $todo)
Run Code Online (Sandbox Code Playgroud)

kas*_*ter 18

详细说明已经说过的话.

假设您了解PHP中的数组.这实际上是一种在给定某个索引的同一变量下对项目"列表"进行分组的方法 - 通常是从0开始的数字整数索引.假设我们要列出索引的英文术语列表,即

Zero
One
Two
Three
Four
Five
Run Code Online (Sandbox Code Playgroud)

使用数组在PHP中表示可以这样做:

$numbers = array("Zero", "One", "Two", "Three", "Four", "Five");
Run Code Online (Sandbox Code Playgroud)

现在,如果我们想要相反的情况呢?将"零"作为键,将0作为值?将非整数作为PHP中数组的键称为关联数组,其中每个元素都使用"key => value"的语法定义,因此在我们的示例中:

$numbers = array("Zero" => 0, "One" => 1, "Two" => 2, "Three" => 3, "Four" => 4, "Five" => 5);
Run Code Online (Sandbox Code Playgroud)

现在的问题是:如果在使用foreach语句时同时需要键和值,该怎么办?答:语法相同!

$numbers = array("Zero" => 0, "One" => 1, "Two" => 2, "Three" => 3, "Four" => 4, "Five" => 5);

foreach($numbers as $key => $value){
    echo "$key has value: $value\n";
}
Run Code Online (Sandbox Code Playgroud)

这会显示出来

Zero has value: 0
One has value: 1
Two has value: 2
Three has value: 3
Four has value: 4
Five has value: 5
Run Code Online (Sandbox Code Playgroud)


Ram*_*mon 11

它用于创建一个关联数组,如下所示:

$arr = array( "name" => "value" );
Run Code Online (Sandbox Code Playgroud)

并且在这样的foreach循环中:

foreach ($arr as $name => $value) {
    echo "My $name is $value";
}
Run Code Online (Sandbox Code Playgroud)


Pek*_*ica 6

您可以使用它与数组一起使用:

array ("key" => "value", "key" => "value")
Run Code Online (Sandbox Code Playgroud)

......或在foreach声明中:

foreach ($my_array as $key => $value)
...
Run Code Online (Sandbox Code Playgroud)