简体   繁体   中英

How to merge multiple dimension array cakephp

I just using function query() of cakePhp. The query will return array something like :

array(
    (int) 0 => array(
        'cate' => array(
            'date' => '2016-12-05',
        ),
        'cate_detail' => array(
            'rel_data_category' => '11'
        ),
        'cate_item' => array(
            'price' => '150.000'
        )
    ),
    (int) 1 => array(
        'cate' => array(
            'date' => '2016-12-05',
        ),
        'cate_detail' => array(
            'rel_data_category' => '10'
        ),
        'cate_item' => array(
            'price' => '250.000'
        )
    ),
    (int) 2 => array(
        'cate' => array(
            'date' => '2016-12-06',
        ),
        'cate_detail' => array(
            'rel_data_category' => '10'
        ),
        'cate_item' => array(
            'price' => '250.000'
        )
    )
)

Now, I want to check if array have the same cate.date will merge array (in this case is elements 0,1 of my array). Output something like :

array(
    (int) 0 => array(
        'cate' => array(
            'date' => '2016-12-05',
        ),
        'cate_detail' => array(
            (int) 0 => array (
                'rel_data_category' => '11',
                'price' => '150.000'
            ),
            (int) 1 => array(
                'rel_data_category' => '10',
                'price' => '250.000'
            )
        )
    ),
    (int) 1 => array(
        'cate' => array(
            'date' => '2016-12-06',
        ),
        'cate_detail' => array(
            (int) 0 => array (
                'rel_data_category' => '10'
                'price' => '250.000'
            )
        )
    )
)

Please help!

You will need to loop through the results and build a new array with the data in the form you want. You can use the CakePHP Hash::extract() method to map the dates to indexes so that you can combine the data for the dates.

For example:-

// Get out all the dates available and then flip the array so that we have a map of dates to indexes
$dates = Hash::extract($results, '{n}.cate.date');
$datesMap = array_flip($dates);
// Define an empty array that we will store the new merged data in
$data = [];
// Loop through the query results and write to the $data array using the map of dates
foreach ($results as $result) {
    $key = $datesMap[$result['cate']['date']];
    $data[$key]['cate'] = $result['cate'];
    $data[$key]['cate_detail'][] = [
        'rel_data_category' => $result['cate_detail']['rel_data_category'],
        'price' => $result['cate_item']['price']
    ];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM