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

Php 基于颜色键的多维数组排列顺序,php,arrays,Php,Arrays,我试图做一个函数,若多维数组中的颜色键出现相同的值,那个么数组的整个元素都可以移动到第6位。我有六种不同的颜色,我想在这样一种方式,相同的颜色不能来之前第六位 例如: 红,红,绿,蓝,蓝,金,青蓝,桃,桃,金,绿 应该是 红,绿,蓝,金,蓝,桃,红,绿,蓝,金,蓝,桃 数组: Array ( [0] => Array ( [id] => 3406 [title] => Brussels

我试图做一个函数,若多维数组中的颜色键出现相同的值,那个么数组的整个元素都可以移动到第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 crossroads 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!
            }
    }
}
数组
(
[0]=>阵列
(
[id]=>3406
[标题]=>布鲁塞尔
[总评论]=>
[评级]=>
[国家]=>阵列
(
[名称]=>比利时
[countryCode]=>BE
)
[状态]=>阵列
(
[名称]=>布鲁塞尔
[州代码]=>BU
)
[摘要]=>布鲁塞尔是比利时和布鲁塞尔首都区的首都。它被讲荷兰语的佛兰德斯及其组成部分佛兰芒-布拉班特省完全包围。作为许多欧洲机构的总部,布鲁塞尔也可能被视为欧盟的首都。布鲁塞尔处于文化的十字路口(北部是日耳曼人,南部是罗曼史),在欧洲扮演着重要角色,布鲁塞尔符合“大熔炉”的原型定义,但仍保留着自己的独特特征。布鲁塞尔市人口为100万,布鲁塞尔大都会区人口略多于200万。
[类别]=>浪漫
[状态]=>2
[img_src]=>http://trekeffect.images.photos.s3.amazonaws.com/1388589592_3406_316011-560x366.jpg
[url]=>/location/belligen/brussel/brussel/3406
[颜色]=>红色
[口号]=>简而言之,拉丁欧
[酒店]=>阵列
(
)
)
[1] =>阵列
(
[id]=>4246
[标题]=>京都
[总评论]=>
[评级]=>
[国家]=>阵列
(
[名称]=>日本
[countryCode]=>JA
)
[状态]=>阵列
(
[名称]=>京都
[stateCode]=>KY
)
[摘要]=>京都是日本的首都已有一千多年的历史,被誉为日本最美丽的城市。然而,游客们可能会惊讶于他们要做多少工作才能看到京都美丽的一面。对这座城市的第一印象将是京都市中心超现代玻璃钢火车站周围的城市扩张尽管如此,坚持不懈的游客很快就会在环绕市中心的寺庙和公园中发现京都隐藏的美丽,并发现这座城市所能提供的远比眼前看到的要多得多。
[类别]=>浪漫
[状态]=>2
[img_src]=>http://trekeffect.images.photos.s3.amazonaws.com/1388607531_4246_240536-560x366.jpg
[url]=>/location/japan/kyoto/kyoto/4246
[颜色]=>青色
[口号]=>无尽的发现
[酒店]=>阵列
(
)
)
[2] =>阵列
(
[id]=>6608
[标题]=>里斯本
[总评论]=>
[评级]=>
[国家]=>阵列
(
[名称]=>葡萄牙
[countryCode]=>PO
)
[状态]=>阵列
(
[名称]=>里斯本
[stateCode]=>LI
)
[摘要]=>葡萄牙首都里斯本近年来经历了一次文艺复兴,当代文化生机勃勃,在当今的欧洲留下了自己的印记。里斯本位于大西洋边缘,是西欧少有的面向海洋、以水为元素的城市之一。里斯本它的白色漂白石灰石建筑、私密的小巷和一种随和的魅力使它成为一个全年受欢迎的旅游目的地。
[类别]=>浪漫
[状态]=>2
[img_src]=>http://trekeffect.images.photos.s3.amazonaws.com/1388588230_6608_654617-560x366.jpg
[url]=>/location/pulation/lisboa/lisbon/6608
[颜色]=>金色
[口号]=>海洋女王
[酒店]=>阵列
(
)
)
[3] =>阵列
(
[id]=>6408
[标题]=>马赛
[总评论]=>
[评级]=>
[国家]=>阵列
(
[名称]=>法国
[countryCode]=>FR
)
[状态]=>阵列
(
[名称]=>普罗旺斯阿尔卑斯蓝海岸
[stateCode]=>PR
)
[摘要]=>马赛有着复杂的历史。它也被称为非洲港,由Phocean(来自希腊城市Phocea)于公元前600年建立,是欧洲最古老的城市之一。该镇与塞尚的绘画和沉睡村庄的陈词滥调“pétanque”相去甚远玩家和Marcel Pagnol小说。马赛有大约一百万居民,是法国人口第二大城市,面积最大。它的人口是不同文化的大熔炉。据说马赛的科摩罗人比科摩罗人多!事实上,马赛人有着不同的种族背景,有着许多不同的文化背景
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;
}
$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);
<?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; 

}