[英]PHP print text randomly once inside a loop
I have data selected from database in object format. 我从数据库中选择了对象格式的数据。 I want to loop it but I also include text randomly to the display. 我想循环播放,但我也将文本随机包含到显示中。 How to add that text to a random place in object? 如何将文本添加到对象中的随机位置? or how to print it randomly once inside the loop? 或者如何在循环内随机打印一次?
//Object data //对象数据
$obj = (object) [ $ obj =(对象)[
'0' => ['name' => 'Banana'], '1' => ['name' => 'Potato'], '2' => ['name' => 'Mango']
]; ];
//addition text will be displayed //将显示附加文本
$text = 'My random text'; $ text ='我的随机文本';
foreach($obj as $d) { foreach($ obj as $ d){
echo $d->name;
} }
Result can be 结果可以是
Banana 香蕉
Potato 土豆
My random text 我的随机文字
Mango 芒果
Or 要么
My random text 我的随机文字
Banana 香蕉
Potato 土豆
Mango 芒果
Or 要么
Banana 香蕉
My random text 我的随机文字
Potato 土豆
Mango 芒果
... ...
I would use a random number. 我会使用一个随机数。 See http://php.net/manual/en/function.rand.php 参见http://php.net/manual/en/function.rand.php
$rand = rand(0, count($yourArray));
Then within your array loop, test the key value of the given item compared to your random number if it matches, echo your text. 然后在您的数组循环中,测试给定项目的键值是否与您的随机数比较(如果匹配),并回显您的文本。
Just find the a random position index from your object data like this. 只需像这样从对象数据中找到一个随机位置索引。
$randPos = rand(0, count($obj)-1);
And put your random text right after this random index of object data while accessing it through look. 并在通过外观访问它的同时,将随机文本放在该对象数据的随机索引之后。
//addition text will be displayed
$text = 'My random text';
foreach($obj as $k => $d) {
echo $d->name;
if($k == $randPos) echo $text;
}
Hope this will help to solve your query !! 希望这将有助于解决您的查询!
Do you have a way of determining how many arrays are stored in your Object? 您是否有办法确定对象中存储了多少个数组?
If so, generate a random number between 0 and $numArraysInObject
- 1 and use a good ol' for ($i = 0; $i < $numArraysInObject; $i++)
. 如果是这样,则生成一个介于0到$numArraysInObject
-1之间的随机数,并for ($i = 0; $i < $numArraysInObject; $i++)
使用一个好的ol'。 When $i
matches $numArraysInObject
, print your random text. 当$i
与$numArraysInObject
匹配时,输出您的随机文本。
$printTime = rand(0, $numArraysInObject);
for ($i = 0; $i < $numArraysInObject; $i++) {
if ($i == $printTime)
echo "My random text";
echo $d -> name;
}
May be you are looking for this .. 可能是您在寻找这个..
foreach($obj as $d) {
$d->name = $d->name . " " . $text; // This concates the text.
echo $d->name;
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.