PHP采样相同值

时间:2018-08-24 23:36:07

标签: php

我有一个包含数据的数组:

array(4) {
    [0]=>
        array(3) {
            ["number"]=>
            string(10) "8678664470"
            ["created_at"]=>
            string(10) "2018-08-11"
            ["title"]=>
            string(18) "Quaerat voluptatem"
        }
    [1]=>
         array(3) {
             ["number"]=>
             string(10) "8678664470"
             ["created_at"]=>
             string(10) "2018-08-11"
             ["title"]=>
             string(15) "Et dolore magna"
        }
    [2]=>
        array(3) {
            ["number"]=>
            string(10) "0535783461"
            ["created_at"]=>
            string(10) "2018-08-15"
            ["title"]=>
            string(27) "Laborious physical exercise"
        }
    [3]=>
        array(3) {
            ["number"]=>
            string(10) "0535783461"
            ["created_at"]=>
            string(10) "2018-08-15"
            ["title"]=>
            string(15) "Natus error sit"
        }
}

如何制作此阵列?需要收集所有title,其中numbercreated_at相同。

array(2) {
  [0]=>
    array(3) {
        ["number"]=>
        string(10) "8678664470"
        ["created_at"]=>
        string(10) "2018-08-11"
        ["title"]=>
            array(2) {
                [0]=>
                    string(18) "Quaerat voluptatem"
                [1]=>
                    string(15) "Et dolore magna"
            }
     }
   [1]=>
     array(3) {
         ["number"]=>
         string(10) "0535783461"
         ["created_at"]=>
         string(10) "2018-08-15"
         ["title"]=>
            array(2) {
                [0]=>
                    string(27) "Laborious physical exercise"
                [1]=>
                    string(15) "Natus error sit"
            }
    }
 }

1 个答案:

答案 0 :(得分:0)

这是一种使用关联数组为已看到的条目累积标题的方法。一口气做到这一点(线性时间复杂度):

function mergeTitles($data) {
    $result = [];

    foreach ($data as $e) {
        $key = $e['number'] . "&" . $e['created_at'];

        if (!array_key_exists($key, $result)) {
            $result[$key] = $e;
            $result[$key]['title'] = [];
        }

        $result[$key]['title'][] = $e['title'];
    }

    return array_values($result);
}

输出:

array(2) {
  [0]=>
  array(3) {
    ["number"]=>
    string(10) "8678664470"
    ["created_at"]=>
    string(10) "2018-08-11"
    ["title"]=>
    array(2) {
      [0]=>
      string(18) "Quaerat voluptatem"
      [1]=>
      string(15) "Et dolore magna"
    }
  }
  [1]=>
  array(3) {
    ["number"]=>
    string(10) "0535783461"
    ["created_at"]=>
    string(10) "2018-08-15"
    ["title"]=>
    array(2) {
      [0]=>
      string(27) "Laborious physical exercise"
      [1]=>
      string(15) "Natus error sit"
    }
  }
}

在此repl上进行测试。