菜鸟问题,关于数组的,请提供算法,谢谢
$arrItem = array(
Array ('code'=>10000,'name'=>'中国','s'=>1),
Array ('code'=>30000,'name'=>'法国','s'=>50),
Array ('code'=>30000,'name'=>'法国','s'=>100),
Array ('code'=>10000,'name'=>'中国','s'=>3),
Array ('code'=>20000,'name'=>'美国','s'=>2),
Array ('code'=>30000,'name'=>'法国','s'=>5)
);
本来是如上数组,我想得到:
$arr = array(
Array ('code'=>10000,'name'=>'中国'),
Array ('code'=>20000,'name'=>'美国'),
Array ('code'=>30000,'name'=>'法国')
);
一时摸不着头绪,求各位提供办法,谢谢了!
------解决方案--------------------
[[email protected] htdocs]$ php test.php<?php /*函数名不区分大小写*/$arrItem = array( Array ('code'=>10000,'name'=>'中国','s'=>1), Array ('code'=>30000,'name'=>'法国','s'=>50), Array ('code'=>30000,'name'=>'法国','s'=>100), Array ('code'=>10000,'name'=>'中国','s'=>3), Array ('code'=>20000,'name'=>'美国','s'=>2), Array ('code'=>30000,'name'=>'法国','s'=>5));foreach ($arrItem as &$elem) { unset($elem['s']);}print_r($arrItem);?><br><font color="#e78608">------解决方案--------------------</font><br>
$arrItem = array(Array ('code'=>10000,'name'=>'中国','s'=>1),Array ('code'=>30000,'name'=>'法国','s'=>50),Array ('code'=>30000,'name'=>'法国','s'=>100),Array ('code'=>10000,'name'=>'中国','s'=>3),Array ('code'=>20000,'name'=>'美国','s'=>2),Array ('code'=>30000,'name'=>'法国','s'=>5));//先删掉二维数组中的最后一个元素for($i = 0; $i ';//删除重复元素$ar_tmp = array();foreach($arrItem as $v) $ar_tmp[] = implode(',', $v);$ar_tmp = array_unique($ar_tmp);$result = array();foreach($ar_tmp as $v) $result[] = explode(',', $v);print_r($result);<br><font color="#e78608">------解决方案--------------------</font><br>
//6楼代码有点问题,木有保留键名,改一下$arrItem = array(Array ('code'=>10000,'name'=>'中国','s'=>1),Array ('code'=>30000,'name'=>'法国','s'=>50),Array ('code'=>30000,'name'=>'法国','s'=>100),Array ('code'=>10000,'name'=>'中国','s'=>3),Array ('code'=>20000,'name'=>'美国','s'=>2),Array ('code'=>30000,'name'=>'法国','s'=>5));function ar_unique($ar) { $result = array(); for($i = 0; $i ';print_r(ar_unique($arrItem));/*Array( [0] => Array ( [code] => 10000 [name] => 中国 ) [1] => Array ( [code] => 30000 [name] => 法国 ) [2] => Array ( [code] => 20000 [name] => 美国 ))*/<br><font color="#e78608">------解决方案--------------------</font><br>来个一劳永逸的函数
$arrItem = array(Array ('code'=>10000,'name'=>'中国','s'=>1),Array ('code'=>30000,'name'=>'法国','s'=>50),Array ('code'=>30000,'name'=>'法国','s'=>100),Array ('code'=>10000,'name'=>'中国','s'=>3),Array ('code'=>20000,'name'=>'美国','s'=>2),Array ('code'=>30000,'name'=>'法国','s'=>5));print_r(array_group($arrItem, 'name', 'code,name'));function array_group($ar, $k, $fields='*') { if(! is_array(current($ar))) return $ar; //是一维数组则返回原数组 if(! is_array($fields)) { if($fields == '*') $fields = array_keys(current($ar)); else $fields = explode(',', $fields); } foreach($ar as $row) { $t = array(); foreach($fields as $p) $t[$p] = $row[$p]; $res[$row[$k]] = $t; } return array_values($res);}<div class="clear"> </div>