@user_tm

Как с помощью цикла foreach правильнее вывести элементы массива в html верстке?

Я новичок в php и у меня такое задание: Создать массив, добавить текст в него, и вывести их используя циклы foreach, for, while. Ко всему этому прилагается верстка, вот она
<div class="fs-lg fw-300 p-5 bg-white border-faded rounded mb-g">
                            <h2>Privacy</h2>
                            <p class="mb-g">
                                Your privacy is important to us at SmartAdmin and the protection, confidentiality and integrity of your personal data are our prime concerns.
                                We will only use your personal information to administer your account, provide the products and services you have requested from us, and to keep you informed about our products and services (if you have consented to this).
                                We only use your data for the purposes for which it was collected and, where relevant, to meet local legal obligations.
                                We will retain your personal information only for as long as is necessary for the purposes for which the information was collected, or as long as is required pursuant to law.
                            </p>
                            <h3>Cookies and other similar technologies</h3>
                            <p>
                                We collect certain data through cookies and similar technologies (e.g. web beacons, tags, device identifiers). Cookies are text files placed on your computer to collect standard internet log information and visitor behaviour information. This information is used to track visitor use of the website and to compile statistical reports on website activity. We register your interaction with our services in order to improve our website, content and services. Our use of such technologies and the data collected is described in more detail in our Cookie Policy. You can manage your cookie preferences through your browser settings.
                            </p>
                        </div>
вот скрин того как выглядит вверстка 5f118b7008617770758157.jpeg
с помощью foreach я сделал два варианта, в первом создал массив и тупо наполнил его элементы из html кода с его содержимым вот так
$arr = ['<h2>Privacy</h2>', '<p class="mb-g">
                                Your privacy is important to us at SmartAdmin and the protection, confidentiality and integrity of your personal data are our prime concerns.
                                We will only use your personal information to administer your account, provide the products and services you have requested from us, and to keep you informed about our products and services (if you have consented to this).
                                We only use your data for the purposes for which it was collected and, where relevant, to meet local legal obligations.
                                We will retain your personal information only for as long as is necessary for the purposes for which the information was collected, or as long as is required pursuant to law.
                            </p>', '<h3>Cookies and other similar technologies</h3>', '<p>
                                We collect certain data through cookies and similar technologies (e.g. web beacons, tags, device identifiers). Cookies are text files placed on your computer to collect standard internet log information and visitor behaviour information. This information is used to track visitor use of the website and to compile statistical reports on website activity. We register your interaction with our services in order to improve our website, content and services. Our use of such technologies and the data collected is described in more detail in our Cookie Policy. You can manage your cookie preferences through your browser settings.
                            </p>'];
и применил цикл foreach следующим образом
foreach ($arr as $value) {
                               echo $value;
                            }
во втором варианте массив я сделал иначе, его элементы это только текст без заголовков и html кода, и для вывода элементов массива в нужном месте html кода мне потребовался еще один дополнительный массив который я заполнил с помощью цикла foreach вот код
<?php // с помощью цикла foreach, где элементы массива это только текст без заголовков и html кода. Для этого потребовался еще один дополнительный массив $newArr = [];
                                $arrText = ['Your privacy is important to us at SmartAdmin and the protection, confidentiality and integrity of your personal data are our prime concerns.
                            We will only use your personal information to administer your account, provide the products and services you have requested from us, and to keep you informed about our products and services (if you have consented to this).
                            We only use your data for the purposes for which it was collected and, where relevant, to meet local legal obligations.
                            We will retain your personal information only for as long as is necessary for the purposes for which the information was collected, or as long as is required pursuant to law.', 'We collect certain data through cookies and similar technologies (e.g. web beacons, tags, device identifiers). Cookies are text files placed on your computer to collect standard internet log information and visitor behaviour information. This information is used to track visitor use of the website and to compile statistical reports on website activity. We register your interaction with our services in order to improve our website, content and services. Our use of such technologies and the data collected is described in more detail in our Cookie Policy. You can manage your cookie preferences through your browser settings.'];
                                $newArr = [];
                                $k = 0;

                                foreach ($arrText as $elem) {
                                     $newArr[$k] = $elem;
                                     $k++;
                                     
                                        }
                                    ?>
в рамках учебного проекта это конечно не так критично, но все же меня терзает мысль, о том что есть более оптимальный вариант, если вы его видите подскажите пожалуйста.
  • Вопрос задан
  • 1002 просмотра
Решения вопроса 1
scottparker
@scottparker
Обычно циклом выводят повторяющиеся элементы, например
<h4>заголовок1</h4>
<div>блок1</div>

<h4>заголовок2</h4>
<div>блок2</div>

<h4>заголовок3</h4>
<div>блок3</div>


и тогда имея массив
$arr = array(array('title' => 'заголовок1', 'block' => 'блок1'),
array('title' => 'заголовок2', 'block' => 'блок2'),
array('title' => 'заголовок3', 'block' => 'блок3'));


можно его вывести с помощью цикла
foreach($arr as $item){
echo '<h4>' . $item['title'] .'</h4>';
echo '<div>' . $item['block'] .'</div>';
}


то есть в массиве у нас есть только значения, при выводи мы их заключаем в теги.
а что во втором случае у вас, я не совсем понял, зачем вы просто скопировали элементы начального массива, в новый
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Stalker_RED
@Stalker_RED
В реальных проектах тексты скорее всего будут в базе данных, а верстка в шаблонах.
Во втором варианте непонятно куда пропала разметка.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы