简体   繁体   中英

HTML Element Arrays - Multidimensional

I'm not 100% sure of the correct terminology of what I'm even asking, but I currently have a form that is being posted that has an array of elements:

<form>
  <input type="text" name="album_songs[0][title]" value="Let It Go" />
  <input type="text" name="album_songs[0][writer]" value="Robert Lopez, Kristen Anderson-Lopez" />
  <input type="text" name="album_songs[0][composer]" value="Frozen" />
  <input type="text" name="album_songs[0][length]" value="3:44" />
  <input type="text" name="album_songs[0][genre]" value="Soundtrack, Music, Animated" />
  <input type="text" name="album_songs[0][songorder]" value="5" />

  <input type="text" name="album_songs[1][title]" value="Love Is An Open Door" />
  <input type="text" name="album_songs[1][writer]" value="Robert Lopez" />
  <input type="text" name="album_songs[1][composer]" value="Frozen" />
  <input type="text" name="album_songs[1][length]" value="2:07" />
  <input type="text" name="album_songs[1][genre]" value="Soundtrack, Music, Animated" />
  <input type="text" name="album_songs[1][songorder]" value="4" />
</form>

And in my code, I can access these elements like the following:

$songs = $_POST["album_songs"];

foreach($songs as $song) {
    $title = $song["title"];
    $writer = $song["writer"]; // turn into array??
    $composer = $song["composer"];
    $length = $song["length"];
    $genre = $song["genre"]; // turn into array??
    $songorder = $song["songorder"];
}

What I would like to have happen, is not only have an array of songs, but also an array of Writers and Genres. Is this even possible? I tried mocking up something like the following but it did not work:

<input type="text" name="album_songs[4][genre[0]]" value="Soundtrack" />
<input type="text" name="album_songs[4][genre[1]]" value="Music" />
<input type="text" name="album_songs[4][genre[2]]" value="Animated" />

Any suggestions or is it even possible?

I might consider a dropdown, but you almost had it:

<input type="text" name="album_songs[4][genre][]" value="Soundtrack" />
<input type="text" name="album_songs[4][genre][]" value="Music" />
<input type="text" name="album_songs[4][genre][]" value="Animated" />

Gives this:

Array
(
    [4] => Array
        (
            [genre] => Array
                (
                    [0] => Soundtrack
                    [1] => Music
                    [2] => Animated
                )
        )
)

Try to use square bracket syntax to convert your form inputs into an array.

IE :

<input type="text" name="album_songs_title[]" value="Title1" />
<input type="text" name="album_songs_title[]" value="Title2" />

Then, you will be able to browse your datas with a foreach(). I think it might work.

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