创建列表类
<?php
/**
* Created by PhpStorm.
* User: zooeymoon
* Date: 2018/5/6
* Time: 15:06
*/
class Lists{
public $elements = [];
public $pos;
public function __construct()
{
$this->pos = 0;
}
/**
* 清空列表元素
*/
public function clear()
{
$this->elements = [];
$this->pos = 0;
}
/**
* 向列表中添加元素
* @param $element 元素
*/
public function append($element)
{
$this->elements[$this->getSize()] = $element;
}
/**
* 输出列表元素
*/
public function toString()
{
echo implode(",",$this->elements);
}
/**
* 删除列表中的元素
* 成功返回true
* @param $element 要删除的元素
* @return bool
*/
public function remove($element)
{
$foundAt = $this->find($element);
if($foundAt > -1){
array_splice($this->elements,$foundAt,1);
return true;
}
return false;
}
/**
* 查找元素是否在列表中存在
* 存在返回元素位置,不存在返回-1
* @param $element
* @return int
*/
public function find($element)
{
for($i = 0 ; $i < $this->getSize() ; $i++){
if($this->elements[$i] == $element){
return $i;
}
}
return -1;
}
/**
* 返回列表元素的数量
* @return int
*/
public function getSize()
{
return count($this->elements);
}
/**
* 返回当前列表指针位置
* @return int
*/
public function getCurrentPosition()
{
return $this->pos + 1;
}
/**
* 插入元素
* @param $element
* @param $after
* @return bool
*/
public function insert($element,$after)
{
$insertPos = $this->find($after);
if($insertPos > -1){
array_splice($this->elements,$insertPos+1,0,$element);
return true;
}
return false;
}
/***
* 查找某个元素是否在列表中
* @param $element
* @return bool
*/
public function contains($element)
{
return in_array($element,$this->elements);
}
public function front()
{
$this->pos = 0;
}
public function end()
{
$this->pos = count($this->elements)-1;
}
public function prev()
{
if($this->hasPrev()){
$this->pos--;
return true;
}
return false;
}
public function next()
{
if($this->hasNext()){
$this->pos++;
return true;
}
return false;
}
public function hasNext()
{
return $this->pos < count($this->elements)-1;
}
public function hasPrev()
{
return $this->pos > 0;
}
public function moveTo($position){
if($position > 0){
if($position-1 <= count($this->elements)){
$this->pos = $position - 1;
return true;
}
}
return false;
}
public function getElement()
{
return $this->elements[$this->pos];
}
}
class Person{
public $name;
public $sex;
public function __construct($name,$sex)
{
$this->name = $name;
$this->sex = $sex;
}
}
$list = new Lists();
$list->append(new Person("liwenqiang",1));
$list->append(new Person("haha",1));
$list->append(new Person("whatever",2));
$list->append(new Person("hehe",1));
function getSameSexName($list , $sex){
for($list->front();$list->hasNext();$list->next()){
if($list->getElement()->sex == $sex){
echo $list->getElement()->name;
}
}
}
getSameSexName($list,1);