求一維數組組織為“樹形”數組的方法

來源:互聯網
上載者:User
好吧……問題的名字有點兒扯……
有數組輸入如下:
[{id=>'00'},{id=>'01'},{id=>'22'},{id='0001'},{id=>'2234'}]

現在想將這個數組組織為以下形式:
[{id=>'00',children=>{{id=>'0001'}} },{id=>'01',children=>{} },{id=>'22',children=>{{id=>'2234'}} }]

其中的id是字串,位元為雙數位(2、4、6、8……),除了2位的id之外,其餘位元的id總能找到上一級id(即元素A:2234必然能找到id為22【也就是left( 0,len(A[id])-2 )】的元素
雖然多次遍曆也可行,但想能實現以下功能:
1、能正確地進行組織
2、每一次組織之後,原始數組會減少,比如第一次將2位的都處理了,那麼在原始數組中id位元為2的其實就沒有必要了,就全部unset
求教啊~


回複討論(解決方案)

建立一個2維數組 array[id][child] 遍曆一次原始數組就可以了
遇到兩位的判斷是否存在 不存在就插入 遇到不是兩位的就認為是child放到該放的地方

$a = array('4401','00','0001','0002','22','2201');$b = array();for($i = 0; $i < count($a); $i++){    if(strlen($a[$i]) == 2)    {        if(!array_key_exists($a[$i],$b))        {        $b[$a[$i]] = array();      }    }    else    {        $id = substr($a[$i], 0, 2);        if(isset($b[$id]))        {        if(!in_array($a[$i], $b[$id]))        {           $b[$id][] = $a[$i];        }      }      else      {      $b[$id] = array();      $b[$id][] = $a[$i];          }     }}print_r($b);

昨天自己寫的代碼,測試可用未最佳化,但是用了後發現在實際存在中存在問題,所以放棄這種一次性讀取全部資料然後後台組織的方式了。

function sort_dep($deps){//將無序的dep組合成為有序的樹狀結構$step=2;$start=1;$res=array();for($start=1;$start<5;$start++){//大迴圈,即要處理的是第幾級的資料foreach($deps as $k => $v){if(strlen($v['id'])==($start*$step)){put_dep($res,$v);unset($deps[$k]);}}}return $res;}function put_dep(&$res,$v){//將數組放入到$res中去$i=strlen($v['id']);if($i==2){$res[]=$v;}else{//需要尋找是在什麼下面的$prefix=substr($v['id'],0,$i-2);foreach($res as $key=>&$value){if($value['id']==$prefix){$value['children'][]=$v;   //children需在前面設定return true;}}}}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.