php操作数组讨论篇
时间:2011-06-10 来源:龙来则去
<?php
//1.判断该集合中是否有某个字符串
$namesArrays = array("AAAAAAA","BBBBBBBB","CCCCCCCCCC","DDDDDDDDD");
$lookingFor ="AAAAAAA";
if(in_array($lookingFor,$namesArrays))
{
echo "内容!";
}else
{
echo "没有数据";
}
//2.判断该数组中有多少元素
$count = count($namesArrays);
echo "集合数量:".$count."<br/>";
//3.向集合中添加元素,默认的情况下会把元素添加到集合的最后
echo "<span style='color:red'>3.集合中添加元素</span><br/>";
array_push($namesArrays,"LONGJIE");
while(list($key,$value)=each($namesArrays))
{
echo $key.":".$value."<br/>";
}
echo "<span style='color:red'>4.数组的最前面添加元素</span><br/>";
//4.在数组的最前面添加元素
array_unshift($namesArrays,"AAAAAAAAAAAAAAA");
while(list($k,$v)=each($namesArrays))
{
echo $k.":".$v."<br/>";
}
echo "<span style='color:red'>5.两个数组合并</span><br/>";
$array1 = array("red","blue","yellow");
$array2 = array("10001","10002","10003");
$mergearray = array_merge($array1,$array2);
while(list($key,$val)=each($mergearray))
{
echo $key.":".$val."<br/>" ;
}
echo "<span style='color:red'>6.删除数组中最后元素</span><br/>";
$arraypops = array("1001","1002","1003","1004","1005");
$arraypoped =array_pop($arraypops);
while(list($key,$val)=each($arraypops))
{
echo $key.":".$val."<br/>";
}
echo "已删除元素:$arraypoped<br/>";
echo "<span style='color:red'>6.删除数组中第一元素</span><br/>";
$arrayshifts = array("张三","李四","王武");
echo "<span style='color:red'>/*****************原来*****************/</span><br/>";
while(list($key,$val)=each($arrayshifts))
{
echo $key.":".$val."<br/>";
}
$arrayshifted = array_shift($arrayshifts);
echo "<span style='color:red'>/*****************现在*****************/</span><br/>";
while(list($key,$val)=each($arrayshifts))
{
echo "删除:".$key.":".$val."<br/>";
}
echo "删除的元素$arrayshifted<br/>";
echo "<span style='color:red'>7.数组排序</span><br/>";
$fruitArray = array("apple", "orange", "banana", "kiwi", "pear");
/* 对数组进行排序*/
sort($fruitArray);
/*显示每个元素及其序号*/
while (list($key,$value) = each($fruitArray))
{
echo "$key : $value<br>";
}
/*****排序*******/
$a = array("apple", "orange", "banana", "kiwi", "pear");
//排序
sort($a);
/* 对数组进行排序*/
foreach ($a as $k)
{
//echo $a[$k]."=>".$v."<br />";
echo $k."<br/>";
}
?>
直接运行复制运行即可。