1
votes

In building out a Google feed, I am needing a way to return the key in my multidimensional array for age groups based on sizes:

$sizeArray = array("Newborn" => "0-3m", 
                   "Infant" => array("3-6m", "6-12m"), 
                   "Toddler" => array("12-18m", "18-24m", "2T", "3T", "4T", "5"), 
                   "Kids" => array("6", "7", "8")
             );

I'm hoping it would look something similar to this:

findKey("18-24m", $sizeArray);

Which would return: Toddler

If there is a better way to do this, i'm all ears. Thanks in advance!

3
A better way is to restructure your array to be like this: ['0-3m' => 'Newborn', '3-6m' => 'Infant', '6-12m' => 'Infant' etc. Thus you don't need any function at all. - georg

3 Answers

0
votes

You can do something like this:

$sizeArray = array("Newborn" => "0-3m", 
                   "Infant" => array("3-6m", "6-12m"), 
                   "Toddler" => array("12-18m", "18-24m", "2T", "3T", "4T", "5"), 
                   "Kids" => array("6", "7", "8")
             );

foreach($sizeArray as $key => $array) {
    if(is_array($array)) {
        if(array_search('18-24m', $array)) {
            echo $key;
        }
    }
}

Hope it helps! :D

0
votes

I'm afraid you'll have to resort to searching the arrays.

function findKey($size,$array) {
    foreach($array as $groupName => $data) {
        if(is_array($data)){                // first element is not an array...so check it.
            if(in_array($size,$data)) {
                return $groupName;
            }
        }elseif($size == $data){
            return $groupName ;
        }
    }
    return false;
}

This will search each array in your multidimensional array for given size, and return its name if the size is found. If no group is found for given size, it returns false.

0
votes

Create a Function to find the key:

function findKey($findKey, $array)
{
  foreach($array as $key => $val)
  {
    if(in_array($findKey, $val))
      return $key
  }
  return false;
}

now you can pass one array and key to the function to find the key as below example:

 $sizeArray = array("Newborn" => "0-3m", 
                       "Infant" => array("3-6m", "6-12m"), 
                       "Toddler" => array("12-18m", "18-24m", "2T", "3T", "4T", "5"), 
                       "Kids" => array("6", "7", "8")
                 );
findKey("18-24m", $sizeArray);