0

i'm trying to create a joomla component. The component is about generating a sentence. Basicly, here's the code/function that will help me generate it.

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();
}

the problem is when i getCategory() the return value is always different. I try to use if else but still it return different value because of $cat[array_rand($cat)]. Would appreciate if you guys could help me solve this bug

eez
  • 11
  • 3
  • sure. i put it this way Key: subject; Value: he Key: verb; Value: chews Key: preposition; Value: on Key: noun; Value: a school – eez Aug 02 '12 at 03:45
  • the problem is 'chews' is in 'eat' category from db, a 'school' is 'walk' category. The result must be in the same category – eez Aug 02 '12 at 03:46

1 Answers1

0

you have to use array_rend. This function Pick one or more random entries out of an array

See the url:-

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";
?>
Abid Hussain
  • 7,724
  • 3
  • 35
  • 53
  • Got it. so $rand_keys[0] will return any thing the array right? for for my function i just have to $cat = array("walk","reside","eat"); $b = array_rand($cat); return $b[$rand_keys[0]]; – eez Aug 02 '12 at 03:59