views:

17

answers:

1

I'll try and explain this the best I can.

I have an array called $linkSets, and it has array entires that look like:

<string>,<integer>
<string>,<integer>
<string>,<integer>

I also have a priority list, that goes in this order: 22 -> 18 -> 35 -> 34. I would like to check each integer in the $linkSets array, and get the best <string> from the same array entry based on the <integer>.

I wrote up code that looks like this:

foreach($linkSets as $link)
{
    $parts = explode(',', $link);
    if($parts[1] == 22) {
        $best = $parts[0];
        break;
    }
    if($parts[1] == 18) {
        $best = $parts[0];
        break;
    }
    if($parts[1] == 35) {
        $best = $parts[0];
        break;
    }
    if($parts[1] == 34) {
        $best = $parts[0];
        break;
    }
}
echo "best: $best";

But as you can probably see it doesn't work, it doesn't obey the priority list.

I can't think of any way to do this without looping through the $linkSets array multiple times.

Help is appreciated, thanks.

+1  A: 

There are hundreds of ways to approach this problem, here's one relatively simple:

$tmp = array();
foreach($linkSets as $link)
{
    $parts = explode(',', $link);
    $tmp[$parts[1]] = $parts[0];
}

$priority = array(22, 18, 35, 34);    
$best = false;

foreach($priority as $p) {
    if(isset($tmp[$p])) {
        $best = $tmp[$p];
        break;
    }
}

echo "best: $best";

Or even simpler, albeit a bit hackier:

$tmp = array(22 => false, 18 => false, 35 => false, 34 => false);
foreach($linkSets as $link) {
    $parts = explode(',', $link);
    $tmp[$parts[1]] = $parts[0];
}    
$best = current(array_filter($tmp)); // Works if your strings are non-false
echo $best;

Working example:

http://codepad.org/V6tHJAF7

Tatu Ulmanen
That'd perfect, thank you. :)
Wen