这是一个简化的示例。
尝试生成带有变量的句子,这些变量的字符串在每次迭代中都会改变。 例如:
/*
stringText.php
<?php
$sentences = [
"Hello there, $name.",
"Your gender is $gender",
"Are you $age years old?",
]
?>
*/
$attributes = [
['name'=>'anna','age'=>14, 'gender'=>'female'],
['name'=>'frank','age'=>16, 'gender'=>'male'],
['name'=>'dan','age'=>15, 'gender'=>'male'],
['name'=>'lara','age'=>16, 'gender'=>'female'],
];
foreach($attributes as $val){
$name = $val['name'];
$age = $val['age'];
$gender = $val['gender'];
include('stringText.php');
echo $sentences[rand(0,2)].'<br/>';
}
有没有一种方法可以在不每次都调用“ include”的情况下进行操作?也许将include的值存储在变量中或类似的东西中?
答案 0 :(得分:2)
您有两个选择-使您的$sentences
变量成为一个函数,并将值传递给它,并返回一个值;
<?php
function sentences($name, $gender, $age){
$sentences = [
"Hello there, $name.",
"Your gender is $gender",
"Are you $age years old?",
];
return $sentences[rand(0,2)];
}
$attributes = [
['name'=>'anna','age'=>14, 'gender'=>'female'],
['name'=>'frank','age'=>16, 'gender'=>'male'],
['name'=>'dan','age'=>15, 'gender'=>'male'],
['name'=>'lara','age'=>16, 'gender'=>'female'],
];
include('stringText.php');
foreach($attributes as $val){
$name = $val['name'];
$age = $val['age'];
$gender = $val['gender'];
echo sentences($val['name'],$val['gender'],$val['age']).'<br/>';
}
您可以在$val
函数中直接传递sentences()
数组并引用键/值,这将在将来提供更大的灵活性。
或者,您可以使用str_replace()
替换字符串中的标记。例如;
<?php
$sentences = [
"Hello there, {{name}}",
"Your gender is {{gender}}",
"Are you {{age}} years old?",
];
$attributes = [
['name'=>'anna','age'=>14, 'gender'=>'female'],
['name'=>'frank','age'=>16, 'gender'=>'male'],
['name'=>'dan','age'=>15, 'gender'=>'male'],
['name'=>'lara','age'=>16, 'gender'=>'female'],
];
// include('stringText.php');
foreach($attributes as $val){
$name = $val['name'];
$age = $val['age'];
$gender = $val['gender'];
$sentence = $sentences[rand(0,2)];
$sentence = str_replace(array('{{name}}','{{gender}}','{{age}}'),array($val['name'],$val['gender'],$val['age']),$sentence);
echo $sentence.'<br/>';
}
答案 1 :(得分:1)
我想要:
string_text.php
<?php
function sentences($name, $age, $gender)
$s = ["Hello there, $name.", "Your gender is $gender.", "You are $age years old."];
return $s[rand(0, 2)];
}
?>
other_page.php
<?php
require_once 'string_text.php';
$attributes = [
['name'=>'Anna','age'=>14, 'gender'=>'female'],
['name'=>'Frank','age'=>16, 'gender'=>'male'],
['name'=>'Dan','age'=>15, 'gender'=>'male'],
['name'=>'Lara','age'=>16, 'gender'=>'female']
];
foreach($attributes as $a){
$r[] = sentences($a['name'], $a['age'], $a['gender']);
}
echo implode('<br />', $r);
?>
好吧,让我们现实一点吧……我将使用客户端JavaScript处理应该或不需要服务器操作的事情。