开发者

PHP Return result in different group

all

I have a bu开发者_JAVA百科ndle of data like 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

then I separate these data into 2 groups which is

$groupA = range(1, 5)

$groupB = range(6, 10)

For instance, I have $data = array(1, 4) and it will return this belong to Group A. Likewise, $data = array(7,8), it will return to me Group B.

So how can I write a script to let $data = array(1, 4, 6, 7) return me Group A and Group B?

Thank you


You may want to use array_intersect:

$groupA = range(1, 5);
$groupB = range(6, 10);
$data = array(1, 4, 6, 7);
$foundGroups = array();
if(array_intersect($data, $groupA))
    $foundGroups[] = 'A';
if(array_intersect($data, $groupB))
    $foundGroups[] = 'B';
print_r($foundGroups);

Note that an empty array evaluates to false while one with at least one element evaluates to true.

Warning: If you have to work with a lot of groups with many elements you may want to use a manual approach and stop at the first common element found. array_intersect finds all the common elements and you don't really need that.


Do you mean something like this?

$data = array(1, 4, 6, 7)
$groupA = array();
$groupB = array();

foreach ((array) $data as $value) {
    if ($value < 6) {
        $groupA[] = $value;
    } else {
        $groupB[] = $value;
    }
}

Greetz,

XpertEase


Try to use array_intersect with every group... if the intersection in not null it means that some elements are in this group...


$data = range(1,9);

$groupA = array_filter($data, "less");
$groupB = array_filter($data, "more");


function less ($v) {
        return $v < 6;
}

function more ($v) {
        return ! less($v);      
}

See it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜