简体   繁体   中英

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 ?> 

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.

Assuming $values is the main array Try this:

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM