根据键名将大型数组拆分为较小的数组

时间:2011-01-02 12:14:54

标签: php

我有下面的数组,我需要根据[location]键拆分成更小的数组(所以我想要一个.co.uk数组和一个.com数组)。 [location]键不限于.co.uk或.com。

感谢任何帮助。

[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/
    )

2 个答案:

答案 0 :(得分:6)

你可以这样做:

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

然后例如$byLocation['.co.uk'][22]是原始数组的第一项。如果您不想维护原始密钥,只需省略它并使用[]代替。

答案 1 :(得分:0)

我原以为你只需要按如下方式迭代数组:

  1. 检查$ domains数组中当前的“location”是否已知(array_key_exists)。如果它没有添加它。 ($domains[<current key>] = array();

  2. 将当前数据添加为$ domains数组中相关位置键下的新数组。 (array_push($domains[<current key>], array('query'=>XXX, 'x'=>...));