将具有匹配键值的数组移动到新的分组数组

时间:2017-04-05 01:59:49

标签: php arrays sorting

我使用var_dump($ fields);

输出以下输出的PHP数组
array() {
    [ 0 ] => array() {
        [ "state" ] => string( 3 ) "nsw"
        [ "address" ] => string( 13 ) "8 Test Street"
        [ "phone" ] => string( 12 ) "0000 000 000"
        [ "email" ] => string( 15 ) "info@123.com.au"
    }
    [ 1 ] => array() {
        [ "state" ] => string( 2 ) "wa"
        [ "address" ] => string( 13 ) "5 Test Street"
        [ "phone" ] => string( 12 ) "0000 000 000"
        [ "email" ] => string( 15 ) "info@123.com.au"
    }
    [ 2 ] => array() {
        [ "state" ] => string( 3 ) "qld"
        [ "address" ] => string( 13 ) "3 Test Street"
        [ "phone" ] => string( 12 ) "0000 000 000"
        [ "email" ] => string( 15 ) "info@123.com.au"
    }
    [ 3 ] => array() {
        [ "state" ] => string( 3 ) "nsw"
        [ "address" ] => string( 13 ) "1 Test Street"
        [ "phone" ] => string( 12 ) "0000 000 000"
        [ "email" ] => string( 15 ) "info@123.com.au"
    }
}

我想从所有"州"创建一个新阵列。键存在于$ fields中并将相应的值移位,如下所示。

array() {
    [ "nsw" ] => array() {
        [0] => array() {
            [ "address" ] => string( 13 ) "8 Test Street"
            [ "phone" ] => string( 12 ) "0000 000 000"
            [ "email" ] => string( 15 ) "info@123.com.au"
        }
        [1] => array() {
            [ "address" ] => string( 13 ) "1 Test Street"
            [ "phone" ] => string( 12 ) "0000 000 000"
            [ "email" ] => string( 15 ) "info@123.com.au"
        }
    }
    [ "wa" ] => array() {
        [0] => array() {
            [ "address" ] => string( 13 ) "5 Test Street"
            [ "phone" ] => string( 12 ) "0000 000 000"
            [ "email" ] => string( 15 ) "info@123.com.au"
        }
    }
    [ "qld" ] => array() {
        [0] => array() {
            [ "address" ] => string( 13 ) "3 Test Street"
            [ "phone" ] => string( 12 ) "0000 000 000"
            [ "email" ] => string( 15 ) "info@123.com.au"
        }
    }
}

任何人都可以帮忙,一直在寻找答案而没有运气。

谢谢!

2 个答案:

答案 0 :(得分:1)

只是有点逻辑。

$('#input-search').val()

答案 1 :(得分:0)

这应该做得很好。

$grouped = array_reduce($addresses, function ($grouped, $address) {
    return array_merge_recursive($grouped, [
        $address['state'] => [ $address ],
    ]);
}, []);