У меня есть большой фрагмент кода php, который создает раскрывающееся меню, и я хочу свести его к минимуму, загрузив опции выбора из текстового файла. Как это сделать правильно с php?
Пример исходного кода:
$field['options'] = array(
array('value' => 'Anenii Noi', 'text' => 'Anenii Noi', 'depth' => 0),
array('value' => 'Bălţi', 'text' => 'Bălţi', 'depth' => 0),
array('value' => 'Basarabeasca', 'text' => 'Basarabeasca', 'depth' => 0),
....
array('value' => 'Ungheni', 'text' => 'Ungheni', 'depth' => 0)
);
И это то, что я пытаюсь сделать, но безуспешно:
// read a text file with select options
// where each option is a seperate line
$file_array = str_replace("\n","", file($file_path));
// build the list of arrays with select options
foreach ($file_array as $location)
$options .= "array('value' => '" . $location . "', 'text' => '" . $location . "', 'depth' => 0),";
foreach($form['field'] as $k => $field) {
// replace the big list of arrays with $options variable
$field['options'] = array($options);
$form['field'][$k] = $field;
break;
}
Похоже, у тебя это было почти. Но вы пытались имитировать чистый PHP-код, который мог бы работать, если позже использовать eval(), но вам нужно подражать его функциям.
// read a text file with select options
// where each option is a seperate line
$file_array = str_replace("\n","", file($file_path));
// build the list of arrays with select options
$options = array();
foreach ($file_array as $location) {
$options[] = array('value' => $location, 'text' => $location, 'depth' => 0);
}
foreach($form['field'] as $k => $field) {
$field['options'] = $options;
$form['field'][$k] = $field;
break;
}
Notice: Undefined index: value ...
и Notice: Undefined index: text ...
$field['options'] = array($options);
теперь эта строка должна быть $field['options'] = $options;