/    Sign up×
Community /Pin to ProfileBookmark

array_rand doesnt work i think

In order to put elements of a text from the table into array i deploy the following code

[CODE]
$sql=mysql_query(“select * from sitecon where konu=’key_kavram'”) or die(mysql_error());
$row=mysql_fetch_object($sql);
$h1a=explode(“@”, $row->icerik);
[/CODE]

It works as it supposed and it insert all the elements separated with “@” into the $h1a array

When i try to get those element randomly i use the following code

[CODE]
$sql=mysql_query(“select * from sitecon where konu=’key_kavram'”) or die(mysql_error());
$row=mysql_fetch_object($sql);
$h1a=explode(“@”, $row->icerik);
$ck=count($h1a)-1;
$ck3=rand(ceil($ck/6), ceil($ck/1.5));
$h1=array_rand($h1a,$ck3);
[/CODE]

$h1 array is filled with numbers not those expected elements from $h1a.

How i can resolve this matter?

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiNov 21.2008 — Bear in mind array_rand returns an array of random keys, not of values. You could do something along the lines of

[code=php]
// array_rand stuff happens here

// turn the values into keys
$h1 = array_flip($h1);

// pull the values from the original array based on these keys
$h1 = array_intersect_key($h1a, $h1);
[/code]


to get an array of values instead of keys, or

[code=php]
// array_rand stuff happens here

while (list($k, $v) = each($h1))
{
// do something with each value here
echo $h1a[$v];
}
[/code]


if you want to process the results in some way immediately (or you could use this method to build your new array, not sure which is quickest to be honest).

Or of course it might be possible to just do it directly in your query depending on exactly what you are trying to achieve (and how your data is structured):

<i>
</i>SELECT * FROM some_table AS r1
JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM some_table)) AS id) AS r2
WHERE r1.id &gt;= r2.id
ORDER BY r1.id ASC
LIMIT 1;


Not 100&#37; sure i've understood your problem correctly so feel free to tell me i'm talking rubbish!
×

Success!

Help @mrtblt spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.4,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...