0

There is custom field "color" in posts with set of hex color codes (all in one custom field, separated with one space). Examples of custom field values for 5 posts:

"000000 f0f0f0 c0c0c0 202020 404040 "
"0000ee 555333 cc0000 602040 003399 "
"9999cc 0000cc 0099ff 204010 552299 "
"406040 ffffff ffcccc 000000 202020 "
"cc0000 99ffcc cc9900 ff9999 000000 "

Posts 1, 4 and 5 have same color "000000" posts 1 and 4 have same color "202020", and posts 2 and 5 have same color "cc0000".

In my example most used single colors would be: "000000", "202020" and "cc0000".

How to show most used single colors (not whole set of colors), for example 20 most used single colors?

0
    //Your color codes
        $str1 = "000000 f0f0f0 c0c0c0 202020 404040 ";
        $str2 = "0000ee 555333 cc0000 602040 003399 ";
        $str3 = "9999cc 0000cc 0099ff 204010 552299 ";
        $str4 = "406040 ffffff ffcccc 000000 202020 ";
        $str5 = "cc0000 99ffcc cc9900 ff9999 000000 ";

    //creating an array and merging all codes
        $final_arr = array_merge( explode(" ",$str1),explode(" ",$str2),explode(" ",$str3),explode(" ",$str4),explode(" ",$str5) );

    //removing all empty elements
        $final_arr = array_filter($final_arr);

        //echo '<pre>'; print_r($final_arr); echo '</pre>';

    //Getting count of each element
        $vals = array_count_values($final_arr);

        //echo '<pre>'; print_r($vals); echo '</pre>';

    //Sorting array in high to low order
        arsort($vals);

//Getting first 3 elements with highest count
        $first_n = array_slice($vals, 0, 3,true);

        echo '<pre>'; print_r($first_n); echo '</pre>';

    //Output
    Array
    (
        [000000] => 3
        [cc0000] => 2
        [202020] => 2
    )
  • Values of "color" custom field are just "examples". I do not have all possible combinations, unless I open one by one posts and copy its custom field value. So, I do not know how I can use code above. – Advanced SEO Aug 1 '15 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.