开发者

Is it possible in PHP for an array to reference itself within its array elements?

I'm wondering if the elements of array can 'know' where they are inside of an array and reference that:

Something like...

$foo = array(
   'This is position ' . $this->开发者_JAVA技巧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


They can't "reference themselves" per se, and certainly not via a $this->position as array elements are not necessarily objects. However, you should be tracking their position as a side-effect of iterating through the array:

// 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);
}


No, PHP's arrays are plain data structures (not objects), without this kind of functionality.

You could track where in the array you are by using each() and keeping track of the keys, but the structure itself can't do it.


As you can see here: http://php.net/manual/en/control-structures.foreach.php

You can do:

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

So you can acces the key via $key in that example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜