Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I use a multidimensional array in a foreach loop, but i dont get the right results back.

array

$mainarray = array( 

    array('field_name'      => 'xx', 
          'email_label'     => 'xxxx', 
          'validation_type' => 'xxxxx',
          'validation_msg'  => 'xxxxxx'),

    array('field_name'      => 'xx', 
          'email_label'     => 'xxxx', 
          'validation_type' => 'xxxxx',
          'validation_msg'  => 'xxxxxx'),

            // more ....
}

foreach loop

foreach($mainarray as $fieldarray){
    foreach($fieldarray as $key => $value){     
        $body .= $value['email_label'].' - '. $value['field_name']; 
    }
}

i need the value's of the key called email_label and field_name, but i dont get the right results back

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

Since your code that appends to $body accesses indexes of $value, your original code was effectively written to work on a three-level array.

If your array is structured as you've posted, you don't need the inner foreach loop.

foreach($mainarray as $fieldarray) {    
    $body .= $fieldarray['email_label'].' - '. $fieldarray['field_name']; 
}
share|improve this answer
    
thanks for the help –  user759235 Aug 25 '11 at 18:30
add comment

You only need one loop for this:

foreach($mainarray as $fieldarray){
    $body .= $fieldarray['email_label'].' - '. $fieldarray['field_name']; 
}
share|improve this answer
    
thanks, this works! –  user759235 Aug 25 '11 at 18:18
    
@user759235 Glad I could help :) When you go to accept an answer though I recommend accepting John Flatness', since he answered quicker than me with the exact same code, and has even added more information to his answer now to help explain why. –  YTowOnt9 Aug 25 '11 at 18:20
add comment

Try to use

foreach($mainarray as $fieldarray){
    $body .= $fieldarray['email_label'].' - '. $fieldarray['field_name']; 
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.