PHP like array_unshift on arrayObject

As the title says: How do you execute array_unshift() on arrayObject , array_push() obtained by doing arrayObject->append() , but what about unshift?

Edit: I forgot to mention that I also need to save the existing keys in this particular case.

+4
source share
4 answers

@Dmitry, @soulmerge your answers were good regarding the original question, but there were no requirements in my editing, but they pointed me in the right direction to achieve what I was expecting here is the solution we came here at work: (work for php > = 5.1)

 public function unshift($value){ $tmp = $this->getArrayCopy(); $tmp = array($value) + $tmp; $this->exchangeArray($tmp); return $this; } 

these examples are not quite the same as the final solution that we need for our specific arrayObject. We use this key in the array values ​​as the key for the values ​​(consider using the rowId database as an index for each value in the collection). let this value "key" here, what the actual structure of the array looks like:

 array( key1 => array(key=>key1,val1=>val1,val2=>val2...), key2 => array(key=>key2,val1=>val1_2,val2=>val2_2...), ... ); 

so our solution looks something like this:

 public function unshift($value){ $tmp = $this->getArrayCopy(); $tmp = array($value['key'],$value) + $tmp; $this->exchangeArray($tmp); return $this; } 

Thanks for your answers, if you find a method that works in php5.0, I am also interested.

+1
source

The ArrayObject API has no function for this. You have several other options:

  • Manually move each element by 1 and set a new value with index 0 (only if you have a numeric index ArrayObject).
  $tmp = NULL; for ($i = 0; $arrayObject->offsetExists($i + 1); $i++) { $tmp = $arrayObject->offsetGet($i + 1); $arrayObject->offsetSet($i + 1, $arrayObject->offsetGet($i)); } $arrayObject->offsetSet($i, $tmp); $arrayObject->offsetSet(0, $new_value); 
  • Write a class derived from ArrayObject and add the prepend function (the implementation may be as follows).
  • Extract the array, call array_unshift() and create a new ArrayObject with the modified array:
  $array = $arrayObject->getArrayCopy(); array_unshift($array, $new_value); $arrayObject->exchangeArray($array); 
+6
source

There is no such function in ArrayObject, but you can subclass it to add everything you need. Try the following:

 class ExtendedArrayObject extends ArrayObject { public function prepend($value) { $array = (array)$this; array_unshift($array, $value); $this->exchangeArray($array); } } 
+4
source
 function prefix($value) { return $this->exchangeArray(array_merge([$value], $this->getArrayCopy())); } 
+2
source

All Articles