简体   繁体   中英

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) [

 '0' => ['name' => 'Banana'], '1' => ['name' => 'Potato'], '2' => ['name' => 'Mango'] 

];

//addition text will be displayed

$text = 'My random text';

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

$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++) . When $i matches $numArraysInObject , print your random text.

$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; 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM