当前位置: 首页 > 后端技术 > PHP

【SPL标准库专题(九)】Datastructures-SplFixedArray

时间:2023-03-29 13:49:34 PHP

SplFixedArray主要处理数组相关的主要函数。不同于普通的php数组,它是以数字为键的定长数组。优点是比普通数组处理更快。类摘要要SplFixedArrayimplementsIterator,ArrayAccess,Countable{/*方法*/public__construct([int$size=0])publicintcount(void)publicmixedcurrent(void)//↓↓导入PHP数组,返回SplFixedArray对象;publicstaticSplFixedArrayfromArray(array$array[,bool$save_indexes=true])//↓↓把SplFixedArray对象数组导出为真实的数组;publicarraytoArray(void)publicintgetSize(void)publicintkey(void)publicvoidnext(void)publicbooloffsetExists(int$index)publicmixedoffsetGet(int$index)publicvoidoffsetSet(int$index,mixed$newval)publicvoidoffsetUnset(int$index)publicvoidrewind(void)publicintsetSize(int$size)publicboolvalid(void)publicvoid__wakeup(void)}Example#Example1:$arr=newSplFixedArray(4);try{$arr[0]='php';$arr[1]='Java';$arr[3]='javascript';$arr[5]='mysql';}catch(RuntimeException$e){//由于是定长数组,$arr超出了定长4;将抛出异常echo$e->getMessage(),':',$e->getCode();}#Example2://publicstaticSplFixedArrayfromArray(array$array[,bool$save_indexes=true])$arr=['4'=>'php','5'=>'javascript','0'=>'node.js','2'=>'linux'];//如果第二个参数默认为true,则保留原来的索引,如果为false,则重新整理索引;//如下,如果重新整理索引,则数组的长度为4;如果长度不重组,则为6;$arrObj=SplFixedArray::fromArray($arr);$arrObj->rewind();while($arrObj->valid()){echo$arrObj->key(),'=>',$arrObj->current();echoPHP_EOL;$arrObj->next();}//↓↓从定长数组对象转换为实数组$arr=$arrObj->toArray();print_r($arr);