数组常用的键值操作与指针操作实例
实例
<?php header("content-type:text/html;charset=utf-8"); /** * 1、常用的键值操作 * 2、数组内部指针操作(巡航) */ $today = ['id'=>1, 'years'=>2018, 'week'=>'周一', 'weather'=>'晴']; echo '<pre>',print_r($today,true); //in_array()判断数组中是否存在某个值 echo in_array('2018',$today) ? 'YES<br>' : 'NO<br>'; //array_key_exists():判断某个键名师傅存在数组中 echo array_key_exists('age',$today) ? 'YES<br>': 'NO<br>'; //array_values():以索引的方式返回数组的值 print_r(array_values($today)); //array_keys():只获取键名 print_r(array_keys($today)); //array_search():以字符串的方式返回指定值的键 $week = array_search('周一',$today); echo $today[$week]; //键值对调 print_r(array_flip($today)); //数组常用的内部的指针操作 echo count($today),'<br>'; //计算当前数组有多少个函数 //key()返回当前元素的键 echo key($today),'<br>'; //current()返回当前元素的值 echo current($today),'<hr>'; next($today); echo key($today),'<br>'; echo current($today),'<hr>'; //复位 reset($today); echo key($today),'<br>'; echo current($today),'<hr>'; //尾部 end($today); echo key($today),'<br>'; echo current($today),'<hr>'; reset($today); //复位 //each()返回当前元素键值的索引与关联描述,并自动下移 print_r(each($today)); print_r(each($today)); //list()讲索引数组中的值,赋值给一组变量 list($key, $value) = each($today); echo $key,'+++++',$value,'<hr>'; //while,list(),each() 遍历数组 reset($today); //复位 while(list($key, $value) = each($today)){ echo $key,'=>', $value,'<br>'; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
数组模拟栈与队列操作实例
实例
<?php header("content-type:text/html;charset=utf-8"); /** * 使用数组来模拟堆栈和队列操作 */ $today = ['id'=>1, 'years'=>2018, 'week'=>'周一', 'weather'=>'晴']; echo '<pre>',print_r($today,true); echo '当前长度'.count($today); //入栈:array_push() 返回的是新数组的长度 = count() array_push($today,'阳光明媚'); echo '当前长度'.count($today); print_r($today); echo array_pop($today),'<br>'; echo array_pop($today),'<br>'; echo array_pop($today),'<br>'; print_r($today); //队 array_shift(), array_unshift() echo array_unshift($today,'明天是个好天气', '后天天气'); print_r($today); array_shift($today); //头部进行删除 print_r($today); //模拟队列操作:增删只能在两端进行,不允许在同一端进行 array_push($today,'周三');//尾部增加入队 print_r($today); array_shift($today);//头部删除出队 print_r($today); array_unshift($today,'明天周四'); //头部入队 print_r($today); array_pop($today);//尾部出队 print_r($today);
运行实例 »
点击 "运行实例" 按钮查看在线实例