2017-01-09 141 views
-1

我只是使用cakePhp的函数query()。该查询将返回数组是这样的:如何合并多维数组cakephp

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

请帮忙!

+2

'cate_total'?该指数突然出现在您期望的输出中?这不是你的输入。也希望输出有一些错位报价检查和批准 –

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

另外,如果我的数组有'item.code',我想检查if(item.code && cate.date)是否具有相同的值。有办法我可以检查一次@drmonkeyninja –

+0

@longhoangvan我不知道你想如何看待,但你应该能够开发我的示例代码上面使用一些if语句也许处理您的情况。 – drmonkeyninja