DCR
DCR

Reputation: 15665

how to access elements of array in another array

I have the following array which contains an array:

Array
(
[title] => SwB Skipper
[today] => 08/11/2016
[crew_name] => Array
    (
        [0] => Array
            (
                [name] => Bob S
            )

        [1] => Array
            (
                [name] => Janet 
            )

        [2] => Array
            (
                [name] => Perry S
            )

        [3] => Array
            (
                [name] => Vinay N
            )

        [4] => Array
            (
                [name] => Pace W
            )

The array is called $values;

I do an:

extract($values);

and then try to access the $crew_name['name'] elements with

<?php foreach ($crew_name['name'] as $crew): ?>

          <option value = "<?php echo $crew['name']; ?>" > 
          <?php echo $crew['name']; ?> </option>

<?php endforeach ?> 

Upvotes: 0

Views: 53

Answers (3)

Indrasis Datta
Indrasis Datta

Reputation: 8618

You could simply use aray_column() function and make your multi array a compact single dimension one. That would make things a lot simpler.

Try this:

<select>
  <?php
      $options = array_column($values["crew_name"], "name");
      foreach($options as $option) {    
   ?>
    <option value = "<?php echo $option; ?>" > 
      <?php echo $option; ?> 
    </option>
   <?php } ?>
</select>

Upvotes: 1

jonju
jonju

Reputation: 2736

Assuming $values is the main array Try this:

foreach($values as $val){
    foreach($val["crew_name"] as $crew){
        echo $crew["name"];
    }
}

Upvotes: 1

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

You're not ready for the ['name'] key at the top level of $crew_name. $crew_name only has numeric keys, so you just need

<?php foreach ($crew_name as $crew): ?>

The rest of it should be ok.

Upvotes: 3

Related Questions