对以下数组进行分组和排序

时间:2016-10-18 14:27:57

标签: php arrays foreach

我想对以下数组进行分组和排序:

 <?php

    $original = array(
    array(
        'country'   => 'France',
        'city'      => 'Paris'
    ),
    array(
        'country'   => 'France',
        'city'      => 'Marseilles'
    ),
    array(
        'country'   => 'France',
        'city'      => 'Bordeaux'
    ),
    array(
        'country'   => 'United States',
        'city'      => 'Chicago'
    ),
    array(
        'country'   => 'United States',
        'city'      => 'Los Angeles'
    ),
    array(
        'country'   => 'United States',
        'city'      => 'New York'
    ), 

);

?>

必须返回原始数组以识别相等的输入并将它们组合成一行。得到这个结果:

   <?php

        $new = array(
            array(
                'country'   => 'France',
                'city'      => 'Paris','Marseilles','Bordeaux'
            ),
            array(
                'country'   => 'United States',
                'city'      => 'Chicago','Los Angeles','New York'
            ), 

        );

   ?>   

我认为通过“foreach”构建器可以实现,但不能达到预期的结果。 有人能帮助我吗?

3 个答案:

答案 0 :(得分:0)

$t = array();
foreach ($original as $city) {
    $t[$city["country"]][] = $city["city"];
}
$new = array();
foreach ($t as $country => $cities) {
    $new[] = array(
        "country" => $country,
        "city" => implode(", ", $cities)
    );
}

答案 1 :(得分:0)

我认为这个任务可以一步解决。

$new = [];
foreach($original as $array)
{
    $country = $array['country'];
    $city = $array['city'];
    if(!isset($new[$country])
    {
        $new[$country]['city'] = '\''.$city.'\'';
        $new[$country]['country'] = $country;
    }
    else
    {
        $new[$country]['city'] .= ',\''.$city.'\'';
    }
}
$new = array_values($new);

答案 2 :(得分:0)

$result = array();
// Load and accumulate all items
foreach ($original as $value) {
  $country = $value['country'];
  if (!isset($result[$country])) {
      $result[$country] = array($value['city']);
    } else {
      $result[$country][] = $value['city'];
    } 
}

// format the output to the desired format
$items = array();
foreach($result as $key=>$value) {
  $items[] = array('country' => $key, 'city' => $value);
}

// display result
echo "<pre>";
print_r($items);
echo "</pre>";