Foreach仅返回一行

时间:2018-12-19 15:19:56

标签: php foreach

我有foreach循环,但是在选择菜单中它只返回一个选项。 Vardump显示了多个结果。我想念什么?

$vars = explode(';', $this->settings['address']);

foreach ($vars as $row) {
    return array(
        'title' => $this->name,
        'options' => array(
            array(
                'id' => 'option_1',
                'icon' => $this->settings['icon'],
                'name' => 'Option 1',
                'description' =>'',
                'fields' => '<select name="address" class="form-control">' . PHP_EOL
                . '<option value="'.$row.'" >'.$row.'</option>' . PHP_EOL
                . '</select>' ,
                'cost' => $this->settings['fee'],
                'tax_class_id' => $this->settings['tax_class_id'],
                'exclude_cheapest' => false,
            ),
        ),
    });
}

2 个答案:

答案 0 :(得分:1)

$vars = explode(';', $this->settings['address']);
$myReturn = array();
foreach ($vars as $row) {
    array_push($myReturn, array(
        'title' => $this->name,
        'options' => array(
            array(
                'id' => 'option_1',
                'icon' => $this->settings['icon'],
                'name' => 'Option 1',
                'description' =>'',
                'fields' => '<select name="address" class="form-control">' . PHP_EOL
                . '<option value="'.$row.'" >'.$row.'</option>' . PHP_EOL
                . '</select>' ,
                'cost' => $this->settings['fee'],
                'tax_class_id' => $this->settings['tax_class_id'],
                'exclude_cheapest' => false,
            ),
        ),
    ));
}
return $myReturn;

答案 1 :(得分:1)

尝试

$vars = explode(';', $this->settings['address']);

$options = [];
foreach ($vars as $row) {
    $options[] = array(
        'id' => 'option_1',
        'icon' => $this->settings['icon'],
        'name' => 'Option 1',
        'description' =>'',
        'fields' => '<select name="address" class="form-control">' . PHP_EOL
            . '<option value="'.$row.'" >'.$row.'</option>' . PHP_EOL
            . '</select>' ,
        'cost' => $this->settings['fee'],
        'tax_class_id' => $this->settings['tax_class_id'],
        'exclude_cheapest' => false,
    );
}

return array(
    'title' => $this->name,
    'options' => $options
);

或者也许

$options = '';

foreach ($vars as $row) {
    $options .= '<option value="' . $row . '" >' . $row . '</option>' . PHP_EOL;
}

$fileds = '<select name="address" class="form-control">' . PHP_EOL . $options . '</select>';

return array(
    'title' => $this->name,
    'options' => array(
        array(
            'id' => 'option_1',
            'icon' => $this->settings['icon'],
            'name' => 'Option 1',
            'description' =>'',
            'fields' => $fileds,
            'cost' => $this->settings['fee'],
            'tax_class_id' => $this->settings['tax_class_id'],
            'exclude_cheapest' => false,
        ),
    ),
});