基于颜色键的多维数组排列顺序

Posted

技术标签:

【中文标题】基于颜色键的多维数组排列顺序【英文标题】:Arrange order of multidimensinal array on the basis of color key 【发布时间】:2014-01-19 15:04:15 【问题描述】:

我正在尝试创建一个函数,如果在多维数组中颜色键出现相同的值,则数组的整个元素可以移动到第 6 位。我有六种不同的颜色,我希望这种颜色不能出现在第 6 位之前。

例如:

红、红、绿、蓝、蓝、金、蓝、桃、桃、金、绿

应该是

红、绿、蓝、金、蓝、桃、红、绿、蓝、金、蓝、桃

数组:

Array
(
    [0] => Array
        (
            [id] => 3406
            [title] => Brussels
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => Belgium
                    [countryCode] => BE
                )

            [state] => Array
                (
                    [name] => Brussels
                    [stateCode] => BU
                )

            [summary] => Brussels is the capital city of Belgium and of Brussels Capital Region. It is entirely surrounded by Dutch-speaking Flanders and its constituent Flemish Brabant province. As headquarters of many European institutions, Brussels might also be considered something of a capital for the European Union. Being at the cros-s-roads of cultures (the Germanic in the North and the Romance in the South) and playing an important role in Europe, Brussels fits the definition of the archetypal "melting pot", but still retains its own unique character. The population of the city of Brussels is 1 million and the population of Brussels metropolitan area is just over 2 million.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388589592_3406_316011-560x366.jpg
            [url] => /location/belgium/brussels/brussels/3406
            [color] => red
            [slogan] => Latin Europe in a nutshell
            [hotels] => Array
                (
                )

        )

    [1] => Array
        (
            [id] => 4246
            [title] => Kyoto
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => Japan
                    [countryCode] => JA
                )

            [state] => Array
                (
                    [name] => Kyoto
                    [stateCode] => KY
                )

            [summary] => Kyoto was the capital of Japan for over a millennium, and carries a reputation as its most beautiful city. However, visitors may be surprised by how much work they will have to do to see Kyoto's beautiful side. Most first impressions of the city will be of the urban sprawl of central Kyoto, around the ultra-modern glass-and-steel train station, which is itself an example of a city steeped in tradition colliding with the modern world. Nonetheless, the persistent visitor will soon discover Kyoto's hidden beauty in the temples and parks which ring the city center, and find that the city has much more to offer than immediately meets the eye.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388607531_4246_240536-560x366.jpg
            [url] => /location/japan/kyoto/kyoto/4246
            [color] => teal
            [slogan] => Endless discovery
            [hotels] => Array
                (
                )

        )

    [2] => Array
        (
            [id] => 6608
            [title] => Lisbon
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => Portugal
                    [countryCode] => PO
                )

            [state] => Array
                (
                    [name] => Lisboa
                    [stateCode] => LI
                )

            [summary] => The capital of Portugal, Lisbon has experienced a renaissance in recent years, with a contemporary culture that is alive and thriving and making its mark in today's Europe. Perched on the edge of the Atlantic Ocean, Lisbon is one of the rare Western European cities that face the ocean and uses water as an element that defines the city. Lisbon enchants travelers with its white bleached limestone buildings, intimate alleyways, and an easy going charm that makes it a popular year round destination.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388588230_6608_654617-560x366.jpg
            [url] => /location/portugal/lisboa/lisbon/6608
            [color] => gold
            [slogan] => Queen of the Sea
            [hotels] => Array
                (
                )

        )

    [3] => Array
        (
            [id] => 6408
            [title] => Marseille
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => France
                    [countryCode] => FR
                )

            [state] => Array
                (
                    [name] => Provence-Alpes-Cote d'Azur
                    [stateCode] => PR
                )

            [summary] => Marseille has a complex history. Also known as Port d`Afrique, it was founded by the Phoceans (from the Greek city of Phocea) in 600 BC and is one of the oldest cities in Europe. The town is a far cry from the Cézanne paintings and Provençal clichés of sleepy villages, "pétanque" players and Marcel Pagnol novels. With around one million inhabitants, Marseille is the second largest city in France in terms of population and the largest in terms of area. Its population is a real melting pot of different cultures. It is also said that there are more Comorian people in Marseille than in Comoros! Indeed, the people of Marseille have varying ethnic backgrounds, with a lot of Italians and Spanish having immigrated to the area after the second world war.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388593398_6408_697894-560x366.jpg
            [url] => /location/france/provence-alpes-cote-d'azur/marseille/6408
            [color] => peach
            [slogan] => C�te d'Azur in your hand
            [hotels] => Array
                (
                )

        )

    [4] => Array
        (
            [id] => 11937
            [title] => Milano
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => Italy
                    [countryCode] => IT
                )

            [state] => Array
                (
                    [name] => Lombardia
                    [stateCode] => LO
                )

            [summary] => Milan has established a long history within the fields of fashion, textiles and design in general. Throughout the late 19th century, the Lombard capital was a major production centre, benefitting from its status as one of the country's salient economic and industrial powerhouses. Milanese fashion, despite taking inspiration from the leading Parisian couture of the time, developed its own approach, which was by nature devoted to sobriety, simplicity and the quality of the fabric. Throughout the 20th century, the city expanded its role as a fashion centre, with a number of rising designers contributing to Milan's image as a stylistic capital. Following this development, Milan emerged in the 1970s and 1980s as one of the world's pre-eminent trendsetters, maintaining this stint well into the 1990s and 2000s and culminating with its entrenchment as one of the "big four" global fashion capitals. As of today, Milan is especially renowned for its role within the prêt-à-porter category of fashion.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388608770_11937_290986-560x366.jpg
            [url] => /location/italy/lombardia/milano/11937
            [color] => blue
            [slogan] => Italy's fashion capital
            [hotels] => Array
                (
                )

        )

    [5] => Array
        (
            [id] => 3722
            [title] => Munich
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => Germany
                    [countryCode] => GM
                )

            [state] => Array
                (
                    [name] => Bayern
                    [stateCode] => BY
                )

            [summary] => Munich, located at the river Isar in the south of Bavaria, is famous for its beautiful architecture, fine culture, and the annual Oktoberfest beer celebration. Munich's cultural scene is second to none in Germany, with the museums even considered by some to outrank Berlin in quality. Many travelers to Munich are absolutely stunned by the quality of the architecture. Although it was heavily damaged by allied bombing during World War II, many of its historic buildings have been rebuilt and the city center appears mostly as it did in the late 1800s including its largest church, the Frauenkirche, and the famous city hall (Neues Rathaus).
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388644879_3722_621878-560x366.jpg
            [url] => /location/germany/bayern/munich/3722
            [color] => red
            [slogan] => Culture, Oktoberfest and Bavaria
            [hotels] => Array
                (
                )

        )

    [6] => Array
        (
            [id] => 6409
            [title] => Paris
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => France
                    [countryCode] => FR
                )

            [state] => Array
                (
                    [name] => Ile-De-France
                    [stateCode] => IL
                )

            [summary] => Paris, the cosmopolitan capital of France, is - with 2.2 million people living in the dense (105 km²) central city and almost 12 million people living in the whole metropolitan area - one of the largest agglomerations in Europe. Located in the north of the country on the river Seine, Paris has the reputation of being the most beautiful and romantic of all cities, brimming with historic associations and remaining vastly influential in the realms of culture, art, fashion, food and design. Dubbed the City of Light (la Ville Lumière) and Capital of Fashion, it is home to some of the world's finest and most luxurious fashion designers and cosmetics, such as Chanel, Christian Dior, Yves Saint-Laurent, Guerlain, Lancôme, L'Oréal, Clarins, etc. A large part of the city, including the River Seine, is a UNESCO World Heritage Site. The city has the second highest number of Michelin-restaurants in the world (after Tokyo) and contains numerous iconic landmarks such as the Eiffel Tower, the Arc de Triomphe, the Notre-Dame Cathedral, the Louvre Museum, Moulin Rouge, Lido etc., making it the third most popular international tourist destination in the world after Bangkok and London, with around 14 million tourists annually. The city of Paris itself is officially divided into 20 districts called arrondissements, numbered from 1 to 20 in a clockwise spiral from the centre of the city (which is known as Kilomètre Zéro and is located at the front of Notre Dame). Arrondissements are named according to their number. You might, for example, stay in the "5th", which would be written as 5e in French. The 12th and 16th arrondissements include large suburban parks, the Bois de Vincennes, and the Bois de Boulogne respectively.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388610018_6409_151621-560x366.jpg
            [url] => /location/france/ile-de-france/paris/6409
            [color] => red
            [slogan] => Visit the City Of Lights
            [hotels] => Array
                (
                )

        )

    [7] => Array
        (
            [id] => 3643
            [title] => Prague
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => Czech Republic
                    [countryCode] => EZ
                )

            [state] => Array
                (
                    [name] => Hlavni Mesto Praha
                    [stateCode] => PR
                )

            [summary] => Prague is the capital city and largest city of the Czech Republic. It is one of the largest cities of Central Europe and has served as the capital of the historic region of Bohemia for centuries.
This magical city of bridges, cathedrals, gold-tipped towers and church domes, has been mirrored in the surface of the swan-filled Vltava River for more than ten centuries. Almost undamaged by WWII, Prague's medieval centre remains a wonderful mixture of cobbled lanes, walled courtyards, cathedrals and countless church spires all in the shadow of her majestic 9th century castle that looks eastward as the sun sets behind her. Prague is also a modern and vibrant city full of energy, music, cultural art, fine dining and special events catering to the independent traveller's thirst for adventure.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388607891_3643_505577-560x366.jpg
            [url] => /location/czech-republic/hlavni-mesto-praha/prague/3643
            [color] => red
            [slogan] => The heart of Bohemia
            [hotels] => Array
                (
                )

        )

    [8] => Array
        (
            [id] => 6713
            [title] => Stockholm
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => Sweden
                    [countryCode] => SW
                )

            [state] => Array
                (
                    [name] => Stockholms Lan
                    [stateCode] => ST
                )

            [summary] => Stockholm is the capital and largest city of Sweden, with nearly 2 million inhabitants within its vicinities. The inner city is made up of 14 islands connected by some 50 bridges on Lake Mälaren, which flows into the brackish Baltic Sea, and passes the Stockholm archipelago with some 24,000 islands and islets.
The city is a cosmopolitan place with both classical and modern architecture, and a captivating Old Town, Gamla Stan. Over 30% of the city area is made up of waterways, and another 30% is made up of green spaces. Air quality is 3rd best of the European capitals - behind Berlin and Copenhagen.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388610724_6713_263943-560x366.jpg
            [url] => /location/sweden/stockholms-lan/stockholm/6713
            [color] => gold
            [slogan] => Beauty on Water
            [hotels] => Array
                (
                )

        )

    [9] => Array
        (
            [id] => 6486
            [title] => Venice
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => Italy
                    [countryCode] => IT
                )

            [state] => Array
                (
                    [name] => Veneto
                    [stateCode] => VE
                )

            [summary] => Venice (Venezia in Italian) is one of the most interesting and lovely places in the world. This sanctuary on a lagoon is virtually the same as it was six hundred years ago, which adds to the fascinating character. Venice has decayed since its heyday and is heavily touristed (there are slightly more tourists than residents), but the romantic charm remains.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388610873_6486_586357-560x366.jpg
            [url] => /location/italy/veneto/venice/6486
            [color] => peach
            [slogan] => Go with the flow
            [hotels] => Array
                (
                )

        )

    [10] => Array
        (
            [id] => 6034
            [title] => Vienna
            [total_reviews] => 
            [rating] => 
            [country] => Array
                (
                    [name] => Austria
                    [countryCode] => AU
                )

            [state] => Array
                (
                    [name] => Wien
                    [stateCode] => WI
                )

            [summary] => Vienna is the capital of the Republic of Austria. It is by far the largest city in Austria, as well as its cultural, economic, and political centre. As the former home of the Habsburg court and its various empires, the city still has the trappings of the imperial capital it once was, and the historic city centre is inscribed on the UNESCO World Heritage List.
            [category] => romantic
            [status] => 2
            [img_src] => http://trekeffect.images.photos.s3.amazonaws.com/1388589759_6034_731692-560x366.jpg
            [url] => /location/austria/wien/vienna/6034
            [color] => red
            [slogan] => The most poetic town in the world
            [hotels] => Array
                (
                )

        )

)


function spaceIdenticalRecords(&$array)
        for ($i=1; $i < count($array); $i++) //loop through the array


              if($array[$i]['value'] === $array[$i - 1]['value'])//look for records that match
                        for ($j= $i + 1; $j < count($array); $j++)
                                if($array[$j] !== $array[$i]) break;
                        


           if ($j+4 > count($array))
                            $length = count($array) - $j -1;
                    else
                            $length = $j - $i + 2;
                    

                    $replace = array_merge(array_slice($array, $j, 3),array($array[$i]));//move the mathing record down 4
                    for ($k = count($replace); count($replace) < $length +1; $k++)$replace = array_merge($replace,array($array[$i]));
                    array_splice($array, $i, count($replace), $replace);//place back in the array
                    $i--; //don't miss records!
            
    

目前我正在使用上述功能。它在某种程度上可以工作,但有时我在 php 中遇到最大的执行错误。任何帮助将不胜感激。

谢谢

【问题讨论】:

6 种不同的颜色是固定的。还是颜色计数将是动态的? 【参考方案1】:

以下函数使用预定义的颜色列表(及其排序位置),但您可以很容易地对其进行修改以处理动态颜色。

function spaceIdenticalRecords3($array) 
    $colors = array('red'   => array('c' => 0, 'p' => 0), 
                    'green' => array('c' => 0, 'p' => 1), 
                    'blue'  => array('c' => 0, 'p' => 2), 
                    'gold'  => array('c' => 0, 'p' => 3), 
                    'teal'  => array('c' => 0, 'p' => 4), 
                    'peach' => array('c' => 0, 'p' => 5));
    /*
     * Build container that is the same size as the original array.
     * The numerical indexes will allow us to avoid a sort on the new
     * array.
     */
    $new_array = array_fill_keys(range(0, (sizeof($array) - 1)), array());
    $size_of_colors = sizeof($colors);
    foreach ( $array as $v ) 
        // Number of times color has been used
        $count = $colors[$v['color']]['c'];
        // Sorted position of the color
        $position = $colors[$v['color']]['p'];
        if ( $count == 0 ) 
            // Color is being used for the first time
            $key = $position;   
         else 
            // Duplicate color, so push it forward
            $key = $position + ( $count * $size_of_colors);
        
        $new_array[$key] = $v;
        $colors[$v['color']]['c']++;
    
    return $new_array;

【讨论】:

【参考方案2】:

试试这个:

$res_clr = array();
$last_pos = 6;
$cur_pos = 0;
foreach($parent_array as $child_array)

    $c = trim($child_array["color"]);
    if(array_search($c,$res_clr)===false) // not found, then add in cur_pos
    

        $res_clr[$cur_pos] = $c;
        $cur_pos++;
    
    else
    

        $res_clr[$last_pos] = $c;
        $last_pos++;
    

ksort($res_clr);
print_r($res_clr);

【讨论】:

这没有保持正确的顺序。 @Dave 可能是。但数组有 6 种颜色,那么我的代码将正常工作。刚刚使用给定值red, red, green, blue, blue, gold, teal, peach, peach, gold, green 进行了测试。因为它有 6 种独特的颜色,所以我的代码工作正常。谢谢。 @ Kumar_v,您的代码没有保持正确的顺序。您的代码返回红色、绿色、蓝色、金色、蓝绿色、桃色、红色、蓝色、金色、绿色。也不会返回与原始多维数组中相同的数据。【参考方案3】:

这将是我的实现,基于给定的约束:

<?php

function spaceIdenticalRecords($items)

  // we keep track of the original total
  $total = count($items);

  // divide the existing items by color
  $bins = array_reduce($items, function(&$memo, $item)
    $memo[$item['color']] = $item;
    return $memo;
  , []);

  $spaced = [];

  // we fill a new array picking up an item from each color, till we are finished
  while($total > 0)

    foreach($bins as $bin)
      $spaced[] = array_shift($bin);
      !empty($bin) && $total--;
    

  

  return $spaced; 


【讨论】:

以上是关于基于颜色键的多维数组排列顺序的主要内容,如果未能解决你的问题,请参考以下文章

多维数组排序

解析没有键的多维 JSON 数组

js多个(N)个数组的的元素组合排序算法,多维数组的排列组合或多个数组之间的排列组合

通过键的多维数组获取数组值

PHP多维数组搜索并获取键的数组[重复]

使用数字键对多维数组进行排序,但保持键相同只是更改顺序