如何合并多维数组cakephp

时间:2017-01-09 10:30:41

标签: php cakephp cakephp-2.0

我只使用cakePhp的函数query()。该查询将返回如下数组:

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'
        )
    )
)

现在,我想检查数组是否具有相同的cate.date合并数组(在这种情况下是我的数组的元素0,1)。输出如下:

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'
            )
        )
    )
)

请帮忙!

1 个答案:

答案 0 :(得分:2)

您需要遍历结果并使用所需表单中的数据构建一个新数组。您可以使用CakePHP Hash::extract() method将日期映射到索引,以便您可以合并日期的数据。

例如: -

// 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']
    ];
}