1

所以一个简单的例子是

$ar = array("some text","more text","yet more text");

foreach($ar as $value){

echo $value."<br>";

}

我得到结果

some text
more text
yet more text

所以我的问题是,当我们在 foreach 循环“$ar as $value”中执行此操作时,我知道 $ar 是数组,但是第二个 $value 是简单变量还是另一个数组呢?因为我们也可以通过以下方式做到这一点

foreach($ar as $value){

echo $value[0]."<br>";

}

这会导致

s
4

5 回答 5

1

在 PHP 中,字符串是字节数组。引用位置0$value0字符串 ( sin some test) 中的位置 ( )

您的实际数组如下所示:

大批
(
    [0] => 一些文字
    [1] => 更多文字
    [2] => 还有更多文字
)

如果要访问数组的索引位置,可以执行以下操作:

foreach($ar as $key=>$val) {
    echo "$key - $val";
}

这将输出:

0 - 一些文字
1 - 更多文字
2 - 还有更多文字
于 2013-02-07T19:04:52.687 回答
1

$value是数组中的一个值,而不是数组本身,除非您有嵌套数组 ( array(array('a','b'),array('b','c')))。但是,下标字符串仍然是可能的,这就是您获得字符串第一个字符的方式。

于 2013-02-07T19:05:23.697 回答
1

问题是$value[0]访问字符串的第一个字符。

字符串在内部表示为数组。所以访问字符串的索引 0 就像访问第一个字符一样。

这就是它打印“s”的原因,因为您的字符串“some text”以 s 开头

你可以看到你的例子如下

array(
    [0] => array(
        [0] => 's',
        [1] => 'o',
        [2] => 'm',
        [3] => 'e',
        //...
    ),
    [1] => array(
        [0] => 'm',
        [1] => 'o',
        [2] => 'r',
        [3] => 'e',
        //...
    ),
    //...
);
于 2013-02-07T19:05:37.103 回答
1

你应该得到

 s m y

在不同的行上。

顺便说一句,br标签是旧帽子。

于 2013-02-07T19:07:02.527 回答
1

String access and modification by character is possible in PHP. What you need to know, and probably didn't know is that while strings are expresses as string, sometimes they can be considered as arrays: let's look at this example:

$text = "The quick brown fox...";

Now, if you were to echo $text[0] you would get the first letter in the string which in this case happens to be T, or if you wanted to modify it, doing $text[0] = "A"; then you will be changing the letter "T" to "A"

Here is a good tutorial from the PHP Manual, It shows you how strings can be accessed/modified by treating them as an array.

<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];

// Get the third character of a string
$third = $str[2];

// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1]; 

// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';

?>

BTW: If you had only wanted to display, the first value inside your array, you could use something like

<?php
$ar = array("some text","more text","yet more text");

for ($i=1; $i<=1; $i++)
  {
  echo $ar[0];
  }

?>
于 2013-02-07T19:09:35.310 回答