首页 > 解决方案 > 如何在对象中一次循环遍历 2 个或多个数组

问题描述

我有一个包含两个数组的 php 对象,我需要同时遍历这两个数组并显示选择选项。table->list应该在值内,并且应该tables->title在选项 HTML 输出内。

这是我的代码:

$tables = new \stdClass();
$tables->list =  ['bmg_contact_us','bmg_volunteer'];
$tables->title = ['Contact us', 'Volunteer'];

<select name="bmg-forms" onchange="submission_frm.submit();">

<?php
foreach ($tables as $key => $table) {
 echo "<option value='" . $tables->list . "'>'" . $tables->title . "'</option>";    
}
?>
</select>

标签: php

解决方案


$tables = new \stdClass();
$tables->list =  ['bmg_contact_us','bmg_volunteer'];
$tables->title = ['Contact us', 'Volunteer'];
$options = array_combine($tables->list,$tables->title);//both array count must be same

输出:

Array
(
    [bmg_contact_us] => Contact us
    [bmg_volunteer] => Volunteer
)

html:

<select name="bmg-forms" onchange="submission_frm.submit();">

<?php
foreach ($options as $key => $value) {
 echo "<option value='" . $key . "'>'" . $value . "'</option>";    
}
?>
</select>

推荐阅读