3

I've created two arrays from strings using explode() one called $labels and the other called $colors. What I'd like to do is check the count of the items in $labels and if there are less items in $colors I'd like the values of the $colors array to be repeated until the count matches. If there are more items in $colors than in $labels I'd like to reduce remove items from the $colors array until it matches the number of items in $labels.

I assume I can use count() or array_legnth() in a conditional to compare the number of items between the two arrays and that I'm going to have to use some kind of while loop but really not sure how to get started.

Is there a better way or function I should use to compare the two arrays? And how would I go about repeating or deleting the items in the second array so that I land up with the same number of items in each?

4

3 回答 3

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);

把它放到一个实用函数中,你会很高兴的。

于 2013-04-21T23:36:53.980 回答
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
)
于 2013-04-21T23:14:51.670 回答
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(...);
}

目前这不是很有效,因为它会遍历整个数组,而不仅仅是差异,但我会将一些代码留给你。:)

或者你可以做一些像你自己的想法的事情,你要么循环遍历较短的数组,要么只用一个值填充它,比如数组中的最后一个值。

if ( count($labels) > count($colors) ) {
   $colors = array_fill(count($colors), count($labels) - count($colors), $colors[count($colors)-1]);  // fill with last value in the array
} else if (count($colors) > count($labels) {
   ...
}

要减少数组中的元素数量,可以使用array_slice

于 2013-04-21T23:03:20.437 回答