在PHP中,数组是否可以在其数组元素中引用自身?

时间:2010-08-30 18:08:55

标签: php arrays

我想知道数组的元素是否能“知道”它们在数组中的位置并引用它:

像...一样的东西。

$foo = array(
   'This is position ' . $this->position,
   'This is position ' . $this->position,
   'This is position ' . $this->position,
),

foreach($foo as $item) {

  echo $item . '\n';
}

//Results:
// This is position 0
// This is position 1
// This is position 2

3 个答案:

答案 0 :(得分:4)

他们本身不能“引用自己”,当然不能通过$this->position,因为数组元素不一定是对象。但是,您应该跟踪它们的位置,作为迭代数组的副作用:

// Sequential numeric keys:
for ($i = 0; $i < count($array); ++$i) { ... }

// Non-numeric or non-sequential keys:
foreach (array_keys($array) as $key) { ... }
foreach ($array as $key => $value) { ... }

// Slow and memory-intensive way (don't do this)
foreach ($array as $item) {
  $position = array_search($item, $array);
}

答案 1 :(得分:2)

不,PHP的数组是纯数据结构(不是对象),没有这种功能。

您可以使用each()并跟踪键来跟踪数组中的位置,但结构本身无法执行此操作。

答案 2 :(得分:0)

正如您在此处所见:http://php.net/manual/en/control-structures.foreach.php

你可以这样做:

foreach($foo as $key => $value) {
  echo $key . '\n';
}

因此,您可以通过该示例中的$ key访问密钥

相关问题