昨天還寫了一篇關于數組合并的技術文章,那里我介紹的是一維數組合并,這里介紹一下php二維數組的合并方法,希望對各位同學會有所幫助哦。
例1:自定義方法合并數組,先看一個二維數組,代碼如下:
- <?php
- Array (
- [0] => Array (
- [A] => store_name
- [B] => 商店一
- )
- [1] => Array (
- [A] => store_owner
- [B] => 小風
- )
- [2] => Array (
- [A] => store_name
- [B] => 商店二
- )
- [3] => Array (
- [A] => store_owner
- [B] => 小磊
- )
- ?>
大家會發現里面有兩個 store_name 和 store_owner,所以我想讓他們合并成下面這樣
- <?php
- Array (
- [0] => Array
- (
- [A] => 商店一
- [B] => 小風
- )
- [1] => Array
- (
- [A] => 商店二
- [B] => 小磊
- )
- ?>
合并方法如下,代碼如下:
- <?php
- $stores = array(); //定義一個空數組
- $store_count=count($showinfo); //統計顯示的次數,這里的$showinfo是我獲取數據庫內容時的一個變量,然后打印出來就是上面剛開始的樣子
- for($i=0;$i<$store_count;$i++)
- {
- $j=$i+1; //將 $i 加 1 跳過 一級 相當于 $j 取得是 鍵值為 奇數的值
- $stores[]=array(
- 'name' =>$showinfo[$i]['value'],
- 'owner'=>$showinfo[$j]['value'],
- );
- $i = $j; // 這里的作用是 相當于 $i 取得是 鍵值為 偶數的值
- }
- ?>
這樣就可以得到上面的結果了,為了讓大家看的更清楚些,我把數據庫表結構寫出來,主要字段如下:
- key value
- store_name 網店一
- store_owner 小風
- store_name 網店二
- store_owner 小磊
通過上面的方法做過后,前臺頁面就可以以一排的方式顯示了,如下
- name owner
- 網店一 小風
- 網店二 小磊
例2,代碼如下:
- <?php
- $arr = array
- (
- 0 => array(
- '1@01,02',
- '2@01,02',
- '4@ALL',
- '3@01',
- '5@01,02,04',
- ),
- 1 => array(
- '1@01,02,03',
- '2@01,02,04',
- '3@ALL',
- '4@01,02',
- '111@01,05',
- '5@03',
- ),
- 2 => array(
- '1@01,02,03',
- '2@02,03,05',
- '3@ALL',
- '4@01,02,03',
- '111@01,05',
- '5@03',
- ),
- );
- $result = array();
- foreach($arr as $items){
- if(is_array($items)){
- foreach($items as $item){
- $item = explode('@', $item);
- if(count($item) != 2){
- continue ;
- }
- $result[$item[0]] .= $item[1].',';
- }
- }
- }
- function reJoin(&$item,$key,$seq){
- $list = array_unique(explode($seq,$item));
- if (in_array('ALL', $list)){
- $item = $key.'@ALL';
- }else{
- $item = $key.'@'.join($seq,$list);
- }
- }
- array_walk($result, 'reJoin',',');
- sort($result);
- var_export($result);
- /**
- * array (
- * 0 => '111@01,05,',
- * 1 => '1@01,02,03,',
- * 2 => '2@01,02,04,03,05,',
- * 3 => '3@ALL',
- * 4 => '4@ALL',
- * 5 => '5@01,02,04,03,',
- * )
- */
- ?>
新聞熱點
疑難解答