按键/值对数组进行分组

时间:2016-01-17 22:19:09

标签: php

我有以下数组:

_wp_page_template

我希望获得的内容如下:

 $array = array(
        array(
            'id' => '1',
            'brand' =>  'Nike',
            'available' => '2016-01-16',
            'price' => '25'
        ),
        array(
            'id' => '2',
            'brand' =>  'Nike',
            'available' => '2016-01-16',
            'price' => '20'
        ),
        array(
            'id' => '3',
            'brand' =>  'Puma',
            'available' => '2016-01-16',
            'price' => '20'
        ),
        array(
            'id' => '4',
            'brand' =>  'Adidas',
            'available' => '2016-01-16',
            'price' => '30'
        ),
        array(
            'id' => '5',
            'brand' =>  'Adidas',
            'available' => '2016-01-15',
            'price' => '32'
        ),
    );

由此数组按品牌分组,并包含 array( 'brand' => 'Nike', 'data' => array( array( '2016-01-16' => '25' ), array( '2016-01-16' => '20' ) ) ), array( 'brand' => 'Puma', 'data' => array( array( '2016-01-16' => '20' ) ) ), array( 'brand' => 'Adidas', 'data' => array( array( '2016-01-16' => '30' ), array( '2016-01-15' => '32' ) ) ); available作为子数组。

理想情况下,我希望能够循环访问数组并获取如下信息:

price

或类似的东西,我可以轻松循环并提取数据。

谢谢

1 个答案:

答案 0 :(得分:0)

以下代码完成了这项工作:

$result = array();
foreach ($array as $record) {
    if (!isset($result[$record['brand']])) {
        $result[$record['brand']] = array(
            'brand' => $record['brand'],
            'data' => array(array($record['available'] => $record['price'])),
        );
    }
    else {
        $result[$record['brand']]['data'][] = array($record['available'] => $record['price']);
    }
}
$result = array_values($result);