我正在尝试创建一个joomla组件。该组件是关于生成一个句子。基本上,这是帮助我生成它的代码/函数。
function getCategory()
{
$cat = array("walk","reside","eat");
return $b = $cat[array_rand($cat)];
}
function getS1() //function 1.1
{
$db = JFactory::getDBO();
$query = "select words from #__wordbank where function = 1.1 order by rand() LIMIT 1";
$db->setQuery($query);
return $db->loadResult();
}
function getV11() //function 2.11
{
$db = JFactory::getDBO();
$b = getCategory();
$query = "select words from #__wordbank where function = 2.11 AND category = '$b' order by rand() LIMIT 1";
$db->setQuery($query);
return $db->loadResult();
}
function getP1() //function p1.1
{
//load preposition
$db = JFactory::getDBO();
$b = getCategory();
$query = "select words from #__wordbank where function = 'p1.1' AND category = '$b' order by rand() LIMIT 1";
$db->setQuery($query);
return $db->loadResult();
}
function getP2() //function p1.2
{
//load noun
$db = JFactory::getDBO();
$b = getCategory();
$query = "select words from #__wordbank where function = 'p1.2' AND category = '$b' order by RAND() limit 1";
$db->setQuery($query);
return $db->loadResult();
}
问题是当getCategory()
返回值总是不同时。我尝试使用if else但由于$cat[array_rand($cat)]
仍然返回不同的值。如果你们能帮我解决这个bug,我将不胜感激
答案 0 :(得分:0)
你必须使用array_rend。此函数从数组中选择一个或多个随机条目
请参阅网址: -
http://php.net/manual/en/function.array-rand.php
<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>