如何在对象中一次遍历2个或更多数组

时间:2019-05-01 08:18:34

标签: php

我有一个包含两个数组的php对象,我需要一次遍历两个数组并显示select选项。 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>

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您需要循环内部数组,然后使用键获取标题。

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

输出:

<option value='bmg_contact_us'>'Contact us'</option>
<option value='bmg_volunteer'>'Volunteer'</option>

https://3v4l.org/i1dcT

答案 2 :(得分:1)

最简单的方法是创建一个关联的数组(from_raw)并对其进行迭代。

在您的示例中:

 $tables->options = [
    'bmg_contact_us' => 'Contact us', 
    'bmg_volunteer' => 'Volunteer'
 ];

 foreach ($tables->options as $value => $text) {
    echo("<option value='$value'>$text</option>");    
 }