2014-02-15 35 views
0

對不起我的英語不好:(轉換「平陣」到「嵌套陣」與CakePHP的(或php)

我想一個「平陣」轉換成「嵌套陣」與CakePHP的(或php )

從該:

$results = array(
    array('customer' => 'John', 'hotel' => 'Sheraton', 'roomtype' => 'Single'), 
    array('customer' => 'John', 'hotel' => 'Sheraton', 'roomtype' => 'Double'), 
    array('customer' => 'John', 'hotel' => 'Sheraton', 'roomtype' => 'Triple'), 
    array('customer' => 'John', 'hotel' => 'Hilton', 'roomtype' => 'Single'), 
    array('customer' => 'Doe', 'hotel' => 'Hilton', 'roomtype' => 'Single'), 
    array('customer' => 'Doe', 'hotel' => 'Hilton', 'roomtype' => 'Double'), 
    array('customer' => 'Doe', 'hotel' => 'Sheraton', 'roomtype' => 'Single') 
); 

成這樣:

$results = array(
    array(
     'customer' => 'Jhon', 
     'children' => array(
      array(
       'hotel' => 'Sheraton', 
       'children' => array(
        array('roomtype' => 'Single'), 
        array('roomtype' => 'Double'), 
        array('roomtype' => 'Triple') 
       ) 
      ), 
      array(
       'hotel' => 'Hilton', 
       'children' => array(
        array('roomtype' => 'Single') 
       ) 
      ), 
     ) 
    ), 
    array(
     'customer' => 'Doe', 
     'children' => array(
      array(
       'hotel' => 'Hilton', 
       'children' => array(
        array('roomtype' => 'Single'), 
        array('roomtype' => 'Double') 
       ) 
      ), 
      array(
       'hotel' => 'Sheraton', 
       'children' => array(
        array('roomtype' => 'Single') 
       ) 
      ), 
     ) 
    ) 
); 

我試圖環(爲,的foreach,而)

我也嘗試設置::巢()CakePHP的效用,但我不找出解決的辦法:(

有沒有「神奇的解決方案」來解決這個問題?

感謝

+0

神奇叫做:的foreach() - 和它的PHP魔術:-) – mark

+0

魔術是被稱爲foreach;) –

回答

1

試試這個

$convert = array(); 
    $customer_key = array(); 
    $hotel_key = array(); 
    $index = 0; 
    foreach ($results as $row) { 
     if (!isset($customer_key[$row['customer']])) { 
      $customer_key[$row['customer']] = $index; 
      $index++; 
     } 
     $key = $customer_key[$row['customer']]; 
     $convert[$key]['customer'] = $row['customer']; 
     if (!isset($hotel_key[$key])) { 
      $hotel_key[$key][$row['hotel']] = 0; 
     } 
     elseif (!isset($hotel_key[$key][$row['hotel']])) { 
      $hotel_key[$key][$row['hotel']] = count($hotel_key[$key]); 
     } 
     $h_key = $hotel_key[$key][$row['hotel']]; 
     $convert[$key]['children'][$h_key]['hotel'] = $row['hotel']; 
     $convert[$key]['children'][$h_key]['children'][]= array('roomtype' => $row['roomtype']); 
    } 

    print_r($convert); 

應該給你的數組轉換爲接受的陣列

+0

感謝它的工作;) –