簡體   English   中英

用cakephp(或php)將“平面數組”轉換為“嵌套數組”

[英]convert a 'flat array' into 'nested array' with cakephp(or 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')
                )
            ),
        )
    )
);

我嘗試了循環(for,foreach,而)

我也嘗試了Set :: nest()cakephp實用程序,但我不知道解決方案:(

是否有任何“魔術解決方案”可以解決此問題?

謝謝

嘗試這個

    $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);

它應該將給定的數組轉換為可接受的數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM