php-重复数组值 [英] php - Repeat array values
本文介绍了php-重复数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组;
[1]=>
array(5) {
["chid"]=>
string(1) "1"
["chtext"]=>
string(9) "Excellent"
["chvotes"]=>
string(2) "13"
["weight"]=>
string(1) "1"
["colour"]=>
string(7) "#b3c7e0"
}
颜色将从文本字段添加到数组.数组可以是任何长度,但颜色的固定长度是4.
The colour is added to the array from a text field. The array could be any length but the colour is at a fixed length of 4.
$poll = $entity->choice; // Array
$poll_colours = array(); // Create new array for colours
$colours = $entity->field_poll_colours['und'][0]['value']; // Get value from text field
$poll_colours = explode(',', $colours); // Explode from comma
foreach($poll as $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);
我要实现的是,如果数组的长度大于4,则重复颜色(1-4).
What I want to achieve is, if the length of the array is more than 4, then repeat the colours (1-4).
所需结果:
[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 the modulus operator to rotate through the colours array.
$colour_count = count($poll_colours);
$poll_colours = array_map('ltrim', $poll_colours);
sort($poll_colours);
foreach($poll as $key => $value) {
$poll[$key]['colour'] = $poll_colours[$key % $colour_count];
}
这篇关于php-重复数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文