2013-04-21 19 views
3

我已經使用explode()創建了兩個字符串數組,其中一個名爲$labels,另一個名爲$colors。我想要做的是檢查$labels中的項目數,並且如果$colors中的項目數較少,我希望$colors數組的值重複,直到計數匹配。如果$colors中的項目多於$labels中的項目,我想從$colors陣列中刪除項目,直到它與$labels中的項目數相匹配。在php數組中重複項目,直到它們匹配另一個數組的計數

我假設我可以在條件中使用count()array_legnth()來比較兩個數組之間的項數,而且我將不得不使用某種while循環但真的不知道如何開始。

是否有更好的方法或函數來比較兩個數組?我該如何去重複或刪除第二個數組中的項目,以便在每個項目中使用相同數量的項目?

+1

立即顯示您的看起來 – hek2mgl 2013-04-21 22:59:25

+0

看到選擇正確的答案,正如我的外觀 - 正如下面的評論所說 - 正是我所用的。 – pushplaybang 2013-05-04 22:50:24

回答

2

這裏是你可以做什麼:

// the two arrays 
$labels = array('a', 'b', 'c', 'd', 'e'); 
$colors = array(1, 2, 3, 4); 


// only if the two arrays don't hold the same number of elements 
if (count($labels) != count($colors)) { 
    // handle if $colors is less than $labels 
    while (count($colors) < count($labels)) { 
     // NOTE : we are using array_values($colors) to make sure we use 
     //  numeric keys. 
     //  See http://php.net/manual/en/function.array-merge.php) 
     $colors = array_merge($colors, array_values($colors)); 
    } 

    // handle if $colors has more than $labels 
    $colors = array_slice($colors, 0, count($labels)); 
} 

// your resulting arrays  
var_dump($labels, $colors); 

把它放到一個效用函數中,你會很好。

+0

儘管所有這三個答案都對我的思維有所幫助,但這一切都讓我頭痛,並且徹底擺脫了第一次之後的解決方案。 – pushplaybang 2013-04-22 05:42:08

1

您可以使用array_walk函數來通過一個或另一個數組並填充值。

if (count($labels) > count($colors)) { 
    array_walk($labels, 'fill_other_array'); 
} else if (count($colors) > count($labels) { 
    array_walk($colors, 'fill_other_array'); 
} 

function fill_other_array() { 
    ... 
    array_fill(...); 
} 

這不是此刻非常有效,因爲它會在整個陣列上,而不是僅僅的區別,但我會留下一些代碼給你。 :)

或者你可以做一些類似你自己的想法,你可以通過較短的數組循環,也可以用數組中的最後一個值來填充它。可以使用array_slice來減少數組中的元素數

+0

將需要更多地使用這些數組函數,因爲我顯然完全不瞭解它們。我不知道在這一點上,我的理解是如何更有效地比較陣列,但我明白你的意思,並將記住,並且需要做一些挖掘:) – pushplaybang 2013-04-22 05:46:37

2

如果你沒有發現前面回答使用此功能:

$labels = array("a","b","c","d","e"); 
$colors = array("green","blue","red"); 

function fillArray($biggerArray,$smallerArray) { 
    $forTimes   = (sizeof($biggerArray)-sizeof($smallerArray)); 
    $finalArray  = $smallerArray; 
    for($i=0;$i < $forTimes ;$i++) { 
     shuffle($smallerArray); 
     array_push($finalArray,$smallerArray[0]); 
    } 
    return $finalArray; 
} 

用法:

$newColorsArray = fillArray($labels,$colors); 
    print_r($newColorsArray); 

它返回:

Array 
(
    [0] => green 
    [1] => blue 
    [2] => red 
    [3] => blue 
    [4] => red 
) 
+0

雖然這對我的思考很有幫助這個問題並不完全是我尋找的結果。 – pushplaybang 2013-04-22 06:03:01

相關問題