开发者

How to reference a item in an array numerically when it has been created as an associative array

I am using PHP 5.3.6

I have the following code below. Everything works fine except for the last line which attempts to to return a value based on the position in the array as opposed to the associative name. Can anyone explain why this takes place and how I can build the array so that I can reference an item either by the associative name or position number?

Thanks.

<?php
class myObject {
  var $Property;
  function myObject($property) {
    $this->Property = $property;
  }
}
$ListOfObjects['form_a'] = new myObject(1); 
$ListOfObjects['form_b'] = new myObject(2); 
$ListOfObjects['form_c'] = new myObject(3); 
$ListOfObjects['form_d'] = new myObject(4); 

echo "<pre>";
print_r($ListOfObjects);
echo "</pre>";

echo "<hr />";
foreach ($ListOfObjects as $key => $val) {
    echo "<li>" . $ListOfObjects[$key]->Property . "</li>";
}

echo "<hr />";
echo "<li>" . $ListOfObjects['form_a']->Property . "</li>"; // Works ok.

//Edit: ---------------------------------------------------开发者_运维技巧---------
//Edit: Everything above is for context only
//Edit: I'm only interested in the line below and why it does not work
//Edit: ------------------------------------------------------------

echo "<li>" . $ListOfObjects[0]->Property . "</li>"; //Does not work.
?>


function value_from_index($a,$k){
    return array_slice($a,$k,1);
}


If you just want the first/last element of an array, try end($array) for the last item without destroying it and reset($array) to get the first.

Don't use reset and end if you're looping through an array as Flambino notes, this indeed results in some unexpected behaviour.

For anything inbetween you'll need to use array_slice()


Not the nicest way of doing it, but effektive and readable:

$i = 0;
$last = count($ListOfObjects);

foreach($ListOfObjects as $obj) {
   if($i == 0) {
       //do something with first object
       $obj->property;
   else if ($i == ($last-1)) {
       //do something with last object
       $obj->property;
   }
}


PHP arrays aren't like arrays you know from most other programming languages, they are more like ordered hash tables / ordered dictionaries - they allow for access by named index and retain order when new items are added. If you want to allow access with numeric indices to such an array you have to define it that way or use one of roundabout ways given in other answers.

In your case you can use a single line of code to allow access by index:

$ListOfObjects += array_values($ListOfObjects);

This will extend your array with the same one but with numeric indices. As objects are always passed by reference, you can access the same object by writing $ListOfObjects['form_b'] and $ListOfObjects[1].

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜