Question

Hi need to intersect two arrays in a special function. the two arrays are:

Array A ( 
[0] => 104-20_140.1 [1] => 104-10_136.1 [2] => 104-40_121.1 [3] => 104-41_122.1 
[4] => 200-42_951.1 [5] => 200-43_952.1 [6] => 200-44_123.1 [7] => 200-45_124.1
[8] => 300-46_125.1 [9] => 300-47_126.1 [10] => 300-48_127.1 [11] => 300-49_128.1
[9] => 380-56_125.1 [10] => 380-57_126.1 [11] => 380-58_127.1 [12] => 380-59_128.1 
)

Array B ( 
[0] => 200 [1] => 300 
)

I need two look at Array A's beginning of the value. Ex. [0] => 104-20_140 and see if the beginning '104' it excists in Array B. If not Array A shall remove it from the result array C.

the output with Array A and B shall have:

Array C ( 
[0] => 200-42_951.1 [1] => 200-43_952.1 [2] => 200-44_123.1 [3] => 200-45_124.1
[4] => 300-46_125.1 [5] => 300-47_126.1 [6] => 300-48_127.1 [7] => 300-49_128.1
)

All shall be calculated in Php

thx for all the help!

Was it helpful?

Solution

Try this:

function startsWith($haystack, $needle) {
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}

$C = array();
foreach ($A as $ka => $va) {
    foreach ($B as $kb => $vb) {
        if (startsWith($va, $vb)) {
            $C[] = $va;
        }
    }
}

example on codepad

OTHER TIPS

Chances are, what you really need is array_uintersect. This will give the option to provide a custom callback which contains the logic on how to check if values intersect.

http://uk3.php.net/manual/en/function.array-uintersect.php

In the callback, you will need to parse out first section before the first "-" using substr or one of the preg functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top