2016-09-07 24 views
1

Ich habe ein Array;php - Array-Werte wiederholen

[1]=> 
    array(5) { 
    ["chid"]=> 
     string(1) "1" 
    ["chtext"]=> 
     string(9) "Excellent" 
    ["chvotes"]=> 
     string(2) "13" 
    ["weight"]=> 
     string(1) "1" 
    ["colour"]=> 
     string(7) "#b3c7e0" 
    } 

Die Farbe wird dem Array aus einem Textfeld hinzugefügt. Das Array kann beliebig lang sein, aber die Farbe ist mit einer festen Länge von 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); 

Was ich erreichen möchte ist, wenn die Länge des Arrays mehr als 4, dann die Farben wiederholen (1-4).

Gewünschtes Ergebnis:

[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... 

Antwort

2

den Modulus-Operator durch die Farben-Array zu drehen.

$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]; 
} 
+0

Es hat funktioniert, danke. Aber nur eine Sache. Die erste wiederholte Farbe ist die vierte Farbe - nicht die erste. –

+0

Korrektur: Die Wiederholung ist in Ordnung, die ursprüngliche Schlüssel/Wert-Reihenfolge ist falsch. –

+1

@Devrim Array-Indizes sollten bei 0 beginnen, nicht 1. – Barmar

Verwandte Themen