php - Repeat array values -
i have array;
[1]=> array(5) { ["chid"]=> string(1) "1" ["chtext"]=> string(9) "excellent" ["chvotes"]=> string(2) "13" ["weight"]=> string(1) "1" ["colour"]=> string(7) "#b3c7e0" }
the colour added array text field. array length colour @ fixed length of 4.
$poll = $entity->choice; // array $poll_colours = array(); // create new array colours $colours = $entity->field_poll_colours['und'][0]['value']; // value text field $poll_colours = explode(',', $colours); // explode comma foreach($poll $key => $value) { $poll[$key]['colour'] = $poll_colours[0]; $poll[$key]['colour'] = ltrim($poll[$key]['colour']); unset($poll_colours[0]); sort($poll_colours); } unset($poll_colours);
what want achieve is, if length of array more 4, repeat colours (1-4).
desired result:
[1]=> array(5) { ["chtext"]=> "a" ["colour"]=> "cyan" } [2]=> array(5) { ["chtext"]=> "b" ["colour"]=> "magenta" } [3]=> array(5) { ["chtext"]=> "c" ["colour"]=> "yellow" } [4]=> array(4) { ["chtext"]=> "d" ["colour"]=> "black" } [5]=> array(5) { ["chtext"]=> "e" ["colour"]=> "cyan" // repeat colour[1] } [6]=> array(5) { ["chtext"]=> "f" ["colour"]=> "magenta" // repeat colour[2] } ... // repeat colour[3] ... // repeat colour[4] ... // repeat colour[1] etc...
use modulus operator rotate through colours array.
$colour_count = count($poll_colours); $poll_colours = array_map('ltrim', $poll_colours); sort($poll_colours); foreach($poll $key => $value) { $poll[$key]['colour'] = $poll_colours[$key % $colour_count]; }
Comments
Post a Comment