数组的各种处理方法:
实例
<?php //编程 : 数组与字符串,变量之间的转换 $book1 = '西游记'; $book2 = '红楼梦'; $book3 = '水浒传'; $book4 = '三国演义'; echo '<pre>'; var_export(compact('book1','book2','book3','book4')); echo '<hr>'; $book = '西游记,红楼梦,水浒传,三国演义'; echo '<pre>'; var_export(explode(',',$book,-1)); echo '<hr>'; //数组元素的回调处理 //1. array_filter():回调处理数组中的每个元素的值,仅返回结果为true的元素 $book5 = ['西游记','红楼梦','','水浒传','三国演义',null,false]; echo '<pre>'; var_export(array_filter($book5)); echo '<hr>'; //2. array_walk():对数组中每个元素的键和值进行处理 $book6 = ['book1'=>'西游记','book2'=>'红楼梦','book3'=>'水浒传','book4'=>'三国演义']; $book7 = ['book11'=>'Journey to the West','book22'=>'The Dream of the Red Chamber ','book33'=>'The Story by the Water Margin','book44'=>'The Romance of the Three Kindoms']; array_walk($book6,function ($value,$key){ echo '<pre>',$key,'--',$value; }); echo '<hr>'; shuffle($book6); echo var_export($book6); echo '<hr>'; $arr2 = array_merge($book6,$book7); echo var_export($arr2); echo '<hr>'; //用for()循环来遍历关联数组 $people = Array( Array('name' => 'lee', 'weight' => 62), Array('name' => 'chaohua', 'weight' => 65) ); for($i = 0, $size = count($people); $i < $size; $i++) { $people[$i]['weight'] = rand(60,70); } echo var_export($people);
运行实例 »
点击 "运行实例" 按钮查看在线实例
运行图:
总结:函数,实在有点复杂!