caffeinehigh
caffeinehigh

Reputation: 309

Looping through multidimensional PHP array goes too many times

I am looping through a multidimensional array and want to get the values by their key. I have it working but rather than loop through each array once it seems to loop through them three times. Code is below:

<?php
$collection_form_fields = array(

    array(
    'group_field_key' => 'field 1',
    'field_key' => 'first_name',
    'field_value' => 'cheese'
  ),
    array(
    'group_field_key' => 'field 2',
    'field_key' => 'last_name',
    'field_value' => 'ham'
  ),
array(
    'group_field_key' => 'field 3',
    'field_key' => 'email',
    'field_value' => 'salami'
  )


);

$output = '';

foreach ( $collection_form_fields as $collection_form_field ) {

  foreach ( $collection_form_field as $value) {

    $output.= '<p>Group field key value: '.$collection_form_field['group_field_key'].'</p>';
    $output.= '<p>Field key value: '.$collection_form_field['field_key'].'</p>';
    $output.= '<p>Field value: '.$collection_form_field['field_value'].'</p>';
    $output.= '<br />';
    

  }

}

echo $output;
?>

Upvotes: 0

Views: 30

Answers (1)

Mo Shal
Mo Shal

Reputation: 1637

This is because you are wrong use foreach , it's loop 3 times and you print all results each time

make your code like this

foreach ( $collection_form_fields as $collection_form_field ) {

  foreach ( $collection_form_field as $key => $value) {

    $output.= '<p>'.$key.' value: '.$value.'</p>';

  }
$output.= '<br />';
}

Upvotes: 2

Related Questions