1

I have the array below which I need to split into smaller arrays based on the [location] key (so I'd like an array of .co.uk and an array of .com). The [location] key is not limited to .co.uk or .com.

Any help is appreciated.

[22] => Array
    (
        [query] => tttt
        [location] => .co.uk
        [x] => 1292889600
        [y] => 1
        [fullurl] => http://www.tttt.com/
    )

[20] => Array
    (
        [query] => tttt
        [location] => .co.uk
        [x] => 1292976000
        [y] => 1
        [fullurl] => http://www.tttt.com/
    )

[21] => Array
    (
        [query] => tttt
        [location] => .com
        [x] => 1292976000
        [y] => 1
        [fullurl] => http://www.tttt.com/
    )

[19] => Array
    (
        [query] => tttt
        [location] => .co.uk
        [x] => 1293062400
        [y] => 1
        [fullurl] => http://www.tttt.com/
    )

[18] => Array
    (
        [query] => tttt
        [location] => .com
        [x] => 1293062400
        [y] => 1
        [fullurl] => http://www.tttt.com/
    )

[17] => Array
    (
        [query] => tttt
        [location] => .co.uk
        [x] => 1293148800
        [y] => 1
        [fullurl] => http://www.tttt.com/
    )

[16] => Array
    (
        [query] => tttt
        [location] => .com
        [x] => 1293148800
        [y] => 1
        [fullurl] => http://www.tttt.com/
    )

[14] => Array
    (
        [query] => tttt
        [location] => .com
        [x] => 1293235200
        [y] => 1
        [fullurl] => http://www.tttt.com/
    )
user489176
  • 113
  • 9

2 Answers2

6

You could do this:

$byLocation = array();
foreach ($arr as $key => $item) {
    if (!isset($byLocation[$item['location']])) {
        $byLocation[$item['location']] = array();
    }
    $byLocation[$item['location']][$key] = $item;
}

Then for example $byLocation['.co.uk'][22] is the first item of your original array. If you don’t want to maintain the original key, just omit it and use [] instead.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • Works perfectly. had to change $byLocation[$item['location']][$key] = $val; to $byLocation[$item['location']][$key] = $item; though. – user489176 Jan 03 '11 at 13:57
0

I'd have thought you simply need to iterate over the array as follows:

  1. Check to see if the current "location" is known (array_key_exists) in a $domains array. If it doesn't add it. ($domains[<current key>] = array();)

  2. Add the current data as a new array under the relevant location key in the $domains array. (array_push($domains[<current key>], array('query'=>XXX, 'x'=>...));)

John Parker
  • 54,048
  • 11
  • 129
  • 129