2

I'm trying to figure out a way to pass either the name of a state or a territory code to an array of sales representatives and have the script return that person's ID. Here is a sample:

$sales_people = array(
    '2' => array(
        'states' => array('NY', 'NJ', 'CT', 'MA', 'VT', 'ME'),
        'codes' => array('CA1', 'US7', 'UT9')
    ),
    '5' => array(
        'states' => array('FL', 'GA', 'SC', 'NC', 'TN'),
        'codes' => array('VA4', 'VA8', 'VA3')
    )
);

If $foo = 'VA4', how would I go about having the script return 5? Similarly, if $foo = 'NJ', how would I have it return 2?

I was thinking of using in_array(), but it would appear as though that doesn't work on multidimensional arrays.

Any insight would be very much appreciated.

4

1 回答 1

2

states如果我理解正确,您想在两个键 (和codes)中搜索值。如果是这样,此代码将完成它:

function sales_search($arr, $needle) {
  foreach ($arr as $id => $data) {
    if (in_array($needle, $data['states'])) {
      return $id;
    }

    if (in_array($needle, $data['codes'])) {
      return $id;
    }
  }
  return false;
}

活样@ideone.com:http: //ideone.com/wmfP2v

echo sales_search($sales_people, 'NJ');  // 2
echo sales_search($sales_people, 'VA4'); // 5
于 2013-09-09T18:36:13.657 回答