0

I have an array ($configOptions) which contains some arrays. Each array ($option) in that array has this structure:

array
  'manufacturer1_sender' => string 'general' (length=7)
  'manufacturer1_mail' => string '[email protected]' (length=16)
  'manufacturer1_template' => string       
  'orderhandling_options_manufacturer1' (length=58)
  'manufacturer1_name' => string 'Acer' (length=4)

The only thing that changes is the number like in manufacturer1_name. The number can be 2,3,4 and so on. Now I have this code:

foreach($configOptions as $option) {
    $name = ??????????;        
}

The $option is the array which I dumped above, how could I access manufacturerN_name in the foreach?

Thanks!

2 Answers 2

2

There's a few ways:

1 - Retrieve all the keys in the sub-array and check each one against a regular expression, capture the result into an array and then use that as the index:

$keys=array_keys($option); //Retrieve all keys
$name='';
foreach ($keys as $key)    //Loop
{
    if (preg_match('/^(manufacturer\d+_name)$/'),$key))
    {
        $name=$key; // We've got a match!
    }
}

2 - If the manufacturerN_name is always the last element in the array, use

$throwaway=end($option); //Retrieve last item in array
$name=key($option)       //Get index of current position

or some similar construct

Sign up to request clarification or add additional context in comments.

Comments

0

You get so by obtaining the number with sscanf­Docs from the first key (manufacturer???_...) and then you can format the name key with sprintf­Docs:

foreach ($configOptions as $option) {
    list($refkey) = each($option);
    $number = sscanf($refkey, 'manufacturer%d_');
    if (NULL === $number) {
        throw new Exception('Could not find number in key "%s" or option %s.', $refkey, print_r($option, true));
    }
    $name = sprintf('manufacturer%d_name', $number);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.