Group variables and loop through them

2019-09-03 12:35发布

问题:

When I just had single variables I used the compact array function to create an array containing variables and their values and looped through them, but now I have multiple variables in a 'group' to loop through:

$details_room_name_1
$details_room_photo_1
$details_room_capacity_seated_1

$details_room_name_2
$details_room_photo_2
$details_room_capacity_seated_2

$details_room_name_2
$details_room_photo_2
$details_room_capacity_seated_2

I want to loop through each 'GROUP' (room) of variables at a time

loop
  echo room name
  print_r room photo array
  echo capacity

回答1:

Using array is better (the best) solution for this task, but if the data structure has to be as you wrote (I don´t know Wordpress), you can use st. like this ugly code.

<?php

$details_room_name_1 = 'room 1';
$details_room_photo_1 = 'photo 1';
$details_room_capacity_seated_1 = 1;

$details_room_name_2 = 'room 2';
$details_room_photo_2 = 'photo 2';
$details_room_capacity_seated_2 = 5;

$details_room_name_3 = 'room 3';
$details_room_photo_3 = 'photo 3';
$details_room_capacity_seated_3 = 8;

for ($i = 1; $i <= 10; $i++) {
    if (!isset(${'details_room_name_' . $i})) continue;

    echo 'room name: ' . ${'details_room_name_' . $i} . '<br>';
    echo 'room photo: ' . ${'details_room_photo_' . $i} . '<br>';
    echo 'room capacity: ' . ${'details_room_capacity_seated_' . $i} . '<br><br>';
}

/*
    returns

    room name: room 1
    room photo: photo 1
    room capacity: 1

    room name: room 2
    room photo: photo 2
    room capacity: 5

    room name: room 3
    room photo: photo 3
    room capacity: 8
*/


标签: php wordpress