在数组中,使用PHP根据键值对项目进行分组

时间:2019-04-13 12:52:35

标签: php arrays

我在PHP中有这个多维数组:

Array
(
    [0] => Array
        (
            [continent] => Europa
            [country] => France
            [capital] => Paris
        )

    [1] => Array
        (
            [continent] => Europa
            [country] => Spain
            [capital] => Madrid
        )
    [2] => Array
        (
            [continent] => Asia
            [country] => Russia
            [capital] => Moscow
        )
)

我如何根据大陆划分国家?

因此,同一大陆上的国家应该组合在一起。

所需的输出应为:

Array
(
    [Europa] => Array
        (
            [country] => France
            [capital] => Paris
        ),
        (
            [country] => Spain
            [capital] => Madrid
        )
    [Asia] => Array
        (
            [country] => Russia
            [capital] => Moscow
        )
)

请问如何使用PHP?

谢谢。

3 个答案:

答案 0 :(得分:1)

您可以创建一个新的数组变量,遍历数据数组以检查是否已创建键,如果尚未创建,则将其创建并将相关数据添加到该键。

<?php
// $data: the name of your array
$grouped_data = array();

for ($i = 0; $i < count($data); $i++) {
    $key = $data[$i]['continent'];

    if (!isset($grouped_data[$key])) {
        $grouped_data[$key] = array();
    }

    $grouped_data[$key][] = array(
        'country' => $data[$i]['country'],
        'capital' => $data[$i]['capital']
    );
}
?>

答案 1 :(得分:1)

$groupByContinent = function(array $list) {
    return array_reduce($list, function($grouped, $item) {
        $grouped[$item['continent']][] = $item;
        return $grouped;
    }, []);
};

$groupedByContinent = $groupByContinent($data);

https://3v4l.org/s6X1c

或者:

$groupByProperty = function(array $list, string $property) {
    return array_reduce($list, function($grouped, $item) use(&$property) {
        $grouped[$item[$property]][] = $item;
        return $grouped;
    }, []);
};

$groupedByContinent = $groupByProperty($data, 'continent');

https://3v4l.org/Be3HL

答案 2 :(得分:0)

您也可以尝试:

$data = array(
    array(  
        "continent" => "Europa",
        "country" => "France",
        "capital" => "Paris",
        ),
   array(
       "continent" => "Europa",
       "country" => "Spain",
       "capital" => "Madrid",
       ),
   array(
       "continent" => "Asia",
       "country" => "Russia",
       "capital" => "Moscow",
       )
);


$group_by = 'continent';
$attributes = array( 'country', 'capital' );

$output = array();
foreach( $data as $country ) {

    if( isset( $country[$group_by] ) ) {

        $one = array();
        foreach( $attributes as $attribute ) {
            if( isset( $country[$attribute] ) ) {
                $one[$attribute] = $country[$attribute];
            }
        }
        $output[ $country[$group_by] ][] = $one;
     }
}


print_r($output);

Demo