-3

I'm quite new in PHP and I'm having problems to even start to solve this issue.

Having this kind of array:

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

I would like to create a new inner array for the ones that contains the same lat and long. In the example above the ones of #1 and #2 have the same lat and log (10.0 and -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"
          )
)

How can I archieve this? Thanks in advance.

Avión
  • 7,963
  • 11
  • 64
  • 105

2 Answers2

1

Use this:

  $result = array();
    foreach ($yourArrayList as $data) {
        $id = $data['lat'];
        if (isset($result[$id])) {
            $result[$id][] = $data;
        } else {
            $result[$id] = array($data);
        }
    }
Andrii Pryimak
  • 797
  • 2
  • 10
  • 33
  • Thanks a lot Andrii, but I think you are just comparing the `lat` and not the `long`. I need to group them when both of them are the same. – Avión Dec 04 '17 at 08:19
  • @Avión When you compare them you get a boolean value, then you can create a loop which utilises something like `array_push` to add the aray. – RAZERZ Dec 04 '17 at 08:24
1

Try this

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

    $result = array_values($result);
vijaykumar
  • 4,658
  • 6
  • 37
  • 54
  • 1
    This will only work if the array fields are 1 after the other and also if key-field lat or long dont exist it will not add them in the array. – pr1nc3 Dec 04 '17 at 08:44
  • 2
    Actually, this doesn't solve his question. He just posted another question with the results obtained here. Silly. Haha. Link: https://stackoverflow.com/questions/47629400/removing-array-of-arrays-for-certain-inner-values-in-php/47629499 – Goma Dec 04 '17 at 08:59