在PHP中按内部值分组数组

时间:2017-12-04 08:13:03

标签: php arrays

我是PHP的新手,我甚至开始解决这个问题。

拥有这种阵列:

Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
          [title] => "Test string 2"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [2] => Array (
          [title] => "Test string 3"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [3] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)

我想为包含相同latlong的内部数组创建一个新的内部数组。在上面的示例中,#1和#2具有相同的lat和log(10.0-23.0)。

Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
            [0] => Array (
                  [title] => "Test string 2"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
            [1] => Array (
                  [title] => "Test string 3"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
          )
   [2] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)

我怎样才能达到这个目的?提前谢谢。

2 个答案:

答案 0 :(得分:1)

使用此:

  $result = array();
    foreach ($yourArrayList as $data) {
        $id = $data['lat'];
        if (isset($result[$id])) {
            $result[$id][] = $data;
        } else {
            $result[$id] = array($data);
        }
    }

答案 1 :(得分:1)

试试这个

    $result = [];
    foreach ($array as $vlaue) {
        $uniqueKey = $vlaue['lat'] .'_'. $vlaue['long'];
        $result[$uniqueKey][] = $value;
    }

    $result = array_values($result);