maddogandnoriko
maddogandnoriko

Reputation: 1002

get array index based on multiple values

I have an array with about 360 keys:

$threadColours['Apricot'] = array(250,180,160,3341,328,826,194,3332,0);
$threadColours['Apricot, Light'] = array(255,230,225,3824,8,833,2605,-1,1);
$threadColours['Apricot, Medium'] = array(255,135,105,3340,329,827,193,-1,2);

I am retrieving a pixel rgb values that came from this array. So I need to get the key where, for example, $threadColours[???][0]=250, [1]=180, [2]=160. I know you can search for a single key but I cannot figure out how to match multiple values. Just to be clear, I have the rgb values I just want to know how to get the key that has all three values in [0],[1],[2] respectively.

Thank you much, Todd

Upvotes: 1

Views: 544

Answers (3)

dfsq
dfsq

Reputation: 193261

$search = array(250, 180, 160);
$color  = null;
foreach ($threadColours as $key => $val) {
    if (array_slice($val, 0, 3) == $search) {
        $color = $key;
        break;
    };
}

Upvotes: 0

anubhava
anubhava

Reputation: 784958

You can use code like this:

$threadColours['Apricot'] = array(250,180,160,3341,328,826,194,3332,0);
$threadColours['Apricot, Light'] = array(255,230,225,3824,8,833,2605,-1,1);
$threadColours['Apricot, Medium'] = array(255,135,105,3340,329,827,193,-1,2);
$needle=array(2605,-1,1); // this is your r,g,b
$startIndex = -1;
$rootElem = "";
foreach ($threadColours as $key => $arr) {
   for ($i=0; $i < count($arr); $i+=3) {
      if ( $arr[$i] == $needle[0] &&
           $arr[$i+1] == $needle[1] &&
           $arr[$i+2] == $needle[2]
         ) {
         $rootElem = $key;
         $startIndex = $i;
         break;
      }
   }
}
printf("rootElem=[%s], startIndex=[%s]\n", $rootElem, $startIndex);

OUTPUT:

rootElem=[Apricot, Light], startIndex=[6]

Upvotes: 0

Susam Pal
Susam Pal

Reputation: 34164

function getColourKey($colours, $r, $g, $b) {
    foreach ($colours as $key => $value)
        if ($value[0] == $r && $value[1] == $g && $value[2] == $b)
            return $key;
    return NULL;
}

Upvotes: 2

Related Questions